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
get jquery `$(this)` id
提问by Gigg
How can I get the id
of 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
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
this
是挂钩事件的 DOM 元素。this.id
是它的ID。无需将其包装在 jQuery 实例中即可获取,该id
属性在所有浏览器上都可靠地反映了该属性。
$("select").change(function() {
alert("Changed: " + this.id);
}
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 event
object'starget
property:
您没有在代码示例中执行此操作,但是如果您正在查看具有多个表单元素的容器,则会为您提供container的 ID 。如果您想要触发事件的元素的 ID,您可以从event
对象的target
属性中获取:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event 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
});