$(this).attr(“id”)不起作用

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

这是代码:

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

HTML:

    Select one one two three Other   

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

由于函数的调用方式(即对函数变量的简单调用), 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(""); } else { $(obj).css({'display' : 'none'}); } } 

更改

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

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

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

 $('#race').change(function() { var select = $(this); var id = select.attr('id'); if(select.val() == 'other') { select.replaceWith(""); } else { select.hide(); } }); 

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

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

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

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

obj.attr('id');

您还可以将整个函数编写为jQuery扩展,因此您可以按照$(’#element’)的方式执行操作.showHideOther();

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

不是它回答了你的问题……只是值得深思。

您期望$(this)参考什么?

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

删除inline event handler ,并完全不引人注意,如

 ​$('​​​​#race').bind('change', function(){ var $this = $(this), id = $this[0].id; if(/^other$/.test($(this).val())){ $this.replaceWith($('', { type: 'text', name: id, id: id })); } });​​​ 

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

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

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

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

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

在这种情况下你想要做的是使用obj.id来获取select标签的id。

你可以做

onchange='showHideOther.call(this);'

代替

onchange='showHideOther(this);'

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