Javascript 为什么可以';我不能使用委托引用id吗?

Javascript 为什么可以';我不能使用委托引用id吗?,javascript,jquery,Javascript,Jquery,当我使用Javascript中的append()函数提供一些html数据时,如: $("#box").append("<button class='primary' id='1'>Button 1</button><button class='primary' id='2'>Button 2</button>"); 它提醒 哎哟!您单击了未定义的按钮 为什么我不能引用id?您需要使用 var btnId = this.id; id属于dom元素

当我使用Javascript中的
append()
函数提供一些html数据时,如:

$("#box").append("<button class='primary' id='1'>Button 1</button><button class='primary' id='2'>Button 2</button>");
它提醒

哎哟!您单击了未定义的按钮

为什么我不能引用id?

您需要使用

var btnId = this.id;
id
属于dom元素,
this
指的是dom元素,但当您说
$(this.id
时,它试图获取未定义的jQuery对象的
id
属性

您可以使用dom元素引用来获取
id
,比如
this.id
,或者使用jQuery的
.attr()
比如
$(this.attr('id')

var btnId = this.id;