[英]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傳遞給function參數?
您可以使用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").on("click", ".btn", function(e) {
var id = $(this).attr('id');
});
要么
$("#list").delegate(".btn", "click", function(e) {
var id = $(this).attr('id');
});
閱讀Jquery上的代表希望對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.