Javascript 获取 jquery `$(this)` id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6346238/
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 21:20:57  来源:igfitidea点击:

get jquery `$(this)` id

javascriptjqueryhtml

提问by Gigg

How can I get the idof the element that triggered the jQuery .change()function? The function itself works properly, but I need a specific action for a selector with id="next".

如何获取id触发 jQuery.change()函数的元素?该函数本身可以正常工作,但我需要对带有id="next".

$("select").change(function() {
    [...snip....]
    alert( $(this).attr('id') );  // <---- not working
}

Any ideas why the alert above isn't working?

任何想法为什么上面的警报不起作用?

回答by T.J. Crowder

thisis the DOM element on which the event was hooked. this.idis its ID. No need to wrap it in a jQuery instance to get it, the idproperty reflects the attribute reliably on all browsers.

this是挂钩事件的 DOM 元素。this.id是它的ID。无需将其包装在 jQuery 实例中即可获取,该id属性在所有浏览器上都可靠地反映了该属性。

$("select").change(function() {    
    alert("Changed: " + this.id);
}

Live example

活生生的例子

You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the eventobject'stargetproperty:

您没有在代码示例中执行此操作,但是如果您正在查看具有多个表单元素的容器,则会为您提供container的 ID 。如果您想要触发事件的元素的 ID,您可以从event对象的target属性中获取:

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});

Live example

活生生的例子

(jQuery ensures that the changeevent bubbles, even on IE where it doesn't natively.)

(jQuery 确保change事件冒泡,即使在它本身不是的 IE 上也是如此。)

回答by John Kalberer

Do you mean that for a select element with an id of "next" you need to perform some specific script?

您的意思是对于 id 为“next”的 select 元素,您需要执行一些特定的脚本吗?

$("#next").change(function(){
    //enter code here
});