如何获取jQuery `$(this)`id

How to get the jQuery `$(this)` id?

本文关键字:this id 何获取 jQuery 获取      更新时间:2023-09-26

如何获取触发jQuery .change()函数的元素的id?函数本身工作正常,但我需要为具有id="next"的选择器执行特定操作。

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

你知道为什么上面的警报不起作用吗?

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

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

实例

您在代码示例中没有这样做,但如果您正在观察一个包含多个表单元素的容器,则会得到容器的ID。如果您想要触发事件的元素的ID,可以从event对象的target属性中获取:

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

实例

(jQuery确保change事件冒泡,即使在IE上也不会冒泡。)

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

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