$(this).attr(“id”) not working

前端 未结 9 775
情书的邮戳
情书的邮戳 2020-12-30 02:55

as the title says, I keep getting \"undefined\" when I try to get the id attribute of an element, basically what I want to do is replace an element with an input box when th

9条回答
  •  误落风尘
    2020-12-30 03:43

    Because of the way the function is called (i.e. as a simple call to a function variable), this is the global object (for which window is an alias in browsers). Use the obj parameter instead.

    Also, creating a jQuery object and the using its attr() method for obtaining an element ID is inefficient and unnecessary. Just use the element's id property, which works in all browsers.

    function showHideOther(obj){ 
        var sel = obj.options[obj.selectedIndex].value;
        var ID = obj.id;
    
        if (sel == 'other') { 
            $(obj).html("");
        } else {
            $(obj).css({'display' : 'none'});
        }
    }
    

提交回复
热议问题