当我在Javascript中提供一些带有append()函数的html数据时,如下所示:
$("#box").append("<button class='primary' id='1'>Button 1</button><button class='primary' id='2'>Button 2</button>");而且,在使用delegate()或on()时,未定义所引用的id:
$("div#box button.primary").on("click",function(){
var btnId = $(this).id;
//Do something Using the Button Id
alert("Ouch! You clicked button " + btnId);
}); 资讯科技警报
唉哟!您单击了未定义的按钮
为什么我不能把身份证转过来?
发布于 2014-07-15 00:54:25
你需要用
var btnId = this.id;id属于dom元素,this引用dom元素,但当您说$(this).id时,它试图获取未定义的jQuery对象的id属性。
您可以使用this.id之类的dom元素引用获取this.id,也可以使用jQuery的.attr()类似于$(this).attr('id')
https://stackoverflow.com/questions/24748367
复制相似问题