jQuery - 点击功能不适用于使用 innerHTML 动态生成的按钮
jQuery - click function does not work on dynamically generated button with innerHTML
我的 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;
});
然后我想为每个生成的按钮添加一个功能,所以我这样写:
$("#list ").click(function(id) {
console.log(id); // to check if the id parameter is passed to the function
// rest of the function
}
我的问题是console.log的输出是"undefined",那么如何将id传递给函数参数呢?
您可以使用 on 函数进行事件委托:
$('#list').on('click','.btn-delete-item',function(){
console.log($(this).attr('id'));
});
$(".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 的工作代码!!
点击事件处理程序的参数是事件对象。处理程序中的范围将是发件人,因此:
$("#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。
$("#list").on("click", ".btn", function(e) {
var id = $(this).attr('id');
});
或
$("#list").delegate(".btn", "click", function(e) {
var id = $(this).attr('id');
});
阅读 Jquery 上的代表
希望这有帮助
我的 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;
});
然后我想为每个生成的按钮添加一个功能,所以我这样写:
$("#list ").click(function(id) {
console.log(id); // to check if the id parameter is passed to the function
// rest of the function
}
我的问题是console.log的输出是"undefined",那么如何将id传递给函数参数呢?
您可以使用 on 函数进行事件委托:
$('#list').on('click','.btn-delete-item',function(){
console.log($(this).attr('id'));
});
$(".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 的工作代码!!
点击事件处理程序的参数是事件对象。处理程序中的范围将是发件人,因此:
$("#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。
$("#list").on("click", ".btn", function(e) {
var id = $(this).attr('id');
});
或
$("#list").delegate(".btn", "click", function(e) {
var id = $(this).attr('id');
});
阅读 Jquery 上的代表 希望这有帮助