简体   繁体   中英

jQuery - click function does not work on dynamically generated button with innerHTML

I have this tag on my HTML file

<tbody id="list" >

in which I integrated some other tags to generate multiple buttons using 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;
});

and then I wanted to add a functionnality to every generated button so I wrote this:

$("#list ").click(function(id) {
 console.log(id); // to check if the id parameter is passed to the function
 // rest of the function
}

My problem is that console.log's output is "undefined", so how can I pass the id to the function parameter?

You can use the on function for event delegation:

$('#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 }); 

This will work!!

check this jsbin for working code!!

The argument to your click event handler is the event object. The scope within the handler will be the sender so:

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

You might also want to look into event delegation using jQuery .

$("#list").on("click", ".btn", function(e) {
  var id = $(this).attr('id');
});

or

$("#list").delegate(".btn", "click", function(e) {
   var id = $(this).attr('id');
});

read Delegates on Jquery Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM