为什么我不能使用委托来引用id ?

Why can't I refer the id using delegate?

本文关键字:引用 id 不能 为什么      更新时间:2023-09-26

当我在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);
}); 

它提醒

哎呀!您单击了未定义按钮

为什么我不能引用id?

你需要使用

var btnId = this.id;

id属于dom元素,this指的是dom元素,但是当你说$(this).id时,它试图获取一个未定义的jQuery对象的id属性。

你可以使用像this.id这样的dom元素引用来获取id,或者使用像$(this).attr('id')这样的jQuery的.attr()