如何获取jQuery`$(this)`ID? [英] How to get the jQuery `$(this)` id?
问题描述
如何获取触发jQuery .change()
函数的元素的 id
?该函数本身可以正常工作,但是我需要对具有 id ="next"
的选择器进行特定的操作.
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"
.
$("select").change(function() {
[...snip....]
alert( $(this).attr('id') ); // <---- not working
}
有什么想法为什么上面的警报不起作用?
Any ideas why the alert above isn't working?
推荐答案
此
是挂钩事件的DOM元素. this.id
是其ID.无需将其包装在jQuery实例中即可获得它, id
属性在所有浏览器上都能可靠地反映该属性.
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.
$("select").change(function() {
alert("Changed: " + this.id);
}
您不是在代码示例中执行此操作,但是如果您正在查看包含多个表单元素的容器,则将为您提供容器的ID.如果您想要触发事件的元素的ID,可以从 event
对象的 target
属性:
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's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery确保 change
事件冒泡,即使在不是本机的IE上也是如此.)
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
这篇关于如何获取jQuery`$(this)`ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!