我的HTML文件中有此标记
<tbody id="list" >
我使用jquery集成了一些其他标签来生成多个按钮:
var html = '';
for (i = 0; i < list.length; i++)
{ html += '<tr>';
html += '<td>';
html +='<a class="btn btn-primary btn-delete-item" id="' +i+'" >Remove</a>';
html += '</td>';
html += '</tr>';
}
document.getElementById("list").innerHTML = html;
});
然后我想为每个生成的按钮添加一个functionnality,所以我写了这个:
$("#list ").click(function(id) {
console.log(id); // to check if the id parameter is passed to the function
// rest of the function
}
我的问题是console.log的输出是“未定义的”,所以如何将id传递给函数参数?
答案 0 :(得分:0)
您可以使用on函数进行事件委派:
$('#list').on('click','.btn-delete-item',function(){
console.log($(this).attr('id'));
});
答案 1 :(得分:0)
$(".btn-primary").on('click',function(id) {
console.log($(this).attr('id')); // to check if the id parameter is passed to the function
// rest of the function
});
这会有效!!
检查此jsbin是否有工作代码!!
答案 2 :(得分:0)
click事件处理程序的参数是事件对象。处理程序中的范围将是发件人:
$("#list").click(function(event)
{
var elem = $(this);
// you can inspect any property of the element here
console.log(elem.attr('id'));
}
您可能还想查看event delegation using jQuery。
答案 3 :(得分:0)
$("#list").on("click", ".btn", function(e) {
var id = $(this).attr('id');
});
或
$("#list").delegate(".btn", "click", function(e) {
var id = $(this).attr('id');
});
阅读Jquery上的代理人 希望这有帮助