簡體   English   中英

jQuery-click函數不適用於使用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傳遞給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的工作代碼!

click事件處理程序的參數是事件對象。 處理程序中的范圍將是發送方,因此:

$("#list").click(function(event) 
{
  var elem = $(this);
  // you can inspect any property of the element here
  console.log(elem.attr('id'));
}

您可能還想使用jQuery研究事件委托

$("#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM