$(this).attr(" id")无效 [英] $(this).attr("id") not working

查看:263
本文介绍了$(this).attr(" id")无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 the value is "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'
        });
    }
}

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>

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

It is probably something small that I am not noticing, what am I doing wrong?

推荐答案

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

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.

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

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("<input type='text' name='" + ID + "' id='" + ID + "' />");
    } else {
        $(obj).css({'display' : 'none'});
    }
}

这篇关于$(this).attr(&quot; id&quot;)无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆