得到jquery` $(this)`id

Gig*_*igg 30 html javascript jquery

如何获取id触发jQuery .change()函数的元素?函数本身可以正常工作,但我需要一个特定的操作选择器id="next".

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

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

T.J*_*der 64

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

$("select").change(function() {    
    alert("Changed: " + this.id);
}
Run Code Online (Sandbox Code Playgroud)

实例

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

$("#container").change(function(event) {
    alert("Field " + event.target.id + " changed");
});
Run Code Online (Sandbox Code Playgroud)

实例

(jQuery确保change事件起泡,即使在IE本身也没有.)


Joh*_*rer 5

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

$("#next").change(function(){
    //enter code here
});
Run Code Online (Sandbox Code Playgroud)