$(this).attr("id")不起作用

Ody*_*3us 15 javascript jquery

正如标题所说,当我尝试获取元素的id属性时,我一直得到"未定义",基本上我想要做的是当值为"other"时用输入框替换元素.

这是代码:

function showHideOther(obj) {
    var sel = obj.options[obj.selectedIndex].value;
    var ID = $(this).attr("id");
    alert(ID);

    if (sel == 'other') {
        $(this).html("<input type='text' name='" + ID + "' id='" + ID + "' />");

    } else {
        $(this).css({
            'display': 'none'
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

HTML:

          <span class='left'><label for='race'>Race: </label></span>
          <span class='right'><select name='race' id='race' onchange='showHideOther(this);'>
            <option>Select one</option>
            <option>one</option>
            <option>two</option>
            <option>three</option>
            <option value="other">Other</option>
          </select>
          </span>
Run Code Online (Sandbox Code Playgroud)

这可能是我不注意的小事,我做错了什么?

fan*_*uka 14

更改

var ID = $(this).attr("id");
Run Code Online (Sandbox Code Playgroud)

var ID = $(obj).attr("id");
Run Code Online (Sandbox Code Playgroud)

您也可以将其更改为使用jQuery事件处理程序:

$('#race').change(function() {
    var select = $(this);
    var id = select.attr('id');
    if(select.val() == 'other') {
        select.replaceWith("<input type='text' name='" + id + "' id='" + id + "' />");
    } else {
        select.hide();
    }
});
Run Code Online (Sandbox Code Playgroud)


doc*_*ryZ 6

您使用this的功能,当你要使用的参数.

你只在回调中使用$(this)...来自选择

$('a').click(function() {
   alert($(this).href);
})
Run Code Online (Sandbox Code Playgroud)

最后,正确的方法(使用您的代码示例)将是这样做的

obj.attr('id');


Tim*_*own 5

由于函数的调用方式(即对函数变量的简单调用),this是全局对象(window浏览器中的别名).请改用obj参数.

此外,创建jQuery对象并使用其attr()获取元素ID的方法是低效且不必要的.只需使用元素的id属性,该属性适用于所有浏览器.

function showHideOther(obj){ 
    var sel = obj.options[obj.selectedIndex].value;
    var ID = obj.id;

    if (sel == 'other') { 
        $(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}
Run Code Online (Sandbox Code Playgroud)