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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3341342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:14:57  来源:igfitidea点击:

$(this).attr("id") not working

javascriptjquery

提问by Odyss3us

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".

正如标题所说,当我尝试获取元素的 id 属性时,我不断收到“未定义”,基本上我想做的是当值为“其他”时用输入框替换元素。

Here is the code:

这是代码:

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'
        });
    }
}

The HTML:

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?

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

采纳答案by Tim Down

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

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

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 idproperty, which works in all browsers.

此外,创建 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'});
    }
}

回答by fantactuka

Change

改变

var ID = $(this).attr("id");

to

var ID = $(obj).attr("id");

Also you can change it to use jQuery event handler:

您也可以将其更改为使用 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();
    }
});

回答by dockeryZ

your using thisin a function, when you should be using the parameter.

this在函数中使用,当你应该使用参数时。

You only use $(this) in callbacks... from selections like

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

$('a').click(function() {
   alert($(this).href);
})

In closing, the proper way (using your code example) would be to do this

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

obj.attr('id');

obj.attr('id');

回答by efritz

You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();

你也可以把你的整个函数写成一个 jQuery 扩展,这样你就可以做一些类似 `$('#element').showHideOther(); 的事情。

(function($) {
    $.extend($.fn, {
        showHideOther: function() {
            $.each(this, function() {
                var Id = $(this).attr('id');
                alert(Id);

                ...

                return this;
            });
        }
    });
})(jQuery);

Not that it answers your question... Just food for thought.

并不是说它回答了您的问题...只是深思熟虑。

回答by jAndy

Remove the inline event handlerand do it completly unobtrusive, like

删除inline event handler并完全不显眼,例如

?$('????#race').bind('change', function(){
  var $this = $(this),
      id    = $this[0].id;

  if(/^other$/.test($(this).val())){
      $this.replaceWith($('<input/>', {
          type: 'text',
          name:  id,
          id: id
      }));
  }
});???

回答by Daniel Earwicker

What are you expecting $(this)to refer to?

你希望$(this)参考什么?

Do you mean sel.attr("id");perhaps?

你的意思是sel.attr("id");也许?

回答by Germán Rodríguez

In the function context "this"its not referring to the select element, but to the page itself

在函数上下文中,“this”不是指选择元素,而是指页面本身

  • Change var ID = $(this).attr("id");to var ID = $(obj).attr("id");
  • 更改var ID = $(this).attr("id");var ID = $(obj).attr("id");

If objis already a jQuery Object, just remove the $() around it.

如果obj已经是一个 jQuery 对象,只需删除它周围的 $() 。

回答by Hrishi

I recommend you to read more about the this keyword.

我建议您阅读有关this 关键字的更多信息。

You cannot expect "this" to select the "select" tag in this case.

在这种情况下,您不能期望“this”选择“select”标签。

What you want to do in this case is use obj.idto get the id of select tag.

在这种情况下,您想要做的是用于obj.id获取 select 标签的 id。

回答by David Hellsing

You can do

你可以做

onchange='showHideOther.call(this);'

onchange='showHideOther.call(this);'

instead of

代替

onchange='showHideOther(this);'

onchange='showHideOther(this);'

But then you also need to replace objwith thisin the function.

但是你还需要在函数中替换objwith this