How to get row index in dynamic table via jQuery

I use jquery to dynamically create table contents on a page, how can I get the index of the line number of this dynamic fairy tale? In the following code, when I click the show more link, I use the index function in the following code, but now it works. How to solve this problem? Thanks.

$.getJSON(JsonURL, function(data){ $.each(data, function(index, item){ var obj = item; books.push(book); }); for (var i = 0; i<obj.length; i++) { var tr=$('<tr></tr>'); $('<td>'+ obj[i].name +'</td>').appendTo(tr); $('<td>'+ obj[i].category +'</td>').appendTo(tr); $('<td><a class=\'showMore\' href=#>'+ 'show more' +'</a></td>').appendTo(tr); tr.appendTo('#tableBody'); }; }); $('a .showMore').on('click', function(event) { var rowindex = $(this).parent().parent().children().index($(this).parent); console.debug('rowindex', rowindex); }); 
+8
javascript jquery
source share
3 answers

For dynamically created elements, you must use event delegation :

The delegation event allows us to attach one event listener to the parent element, which will fire for all children matching the selector, whether these children exist now or are added in the future.

 $('body').on('click', 'a.showMore', function(event) { var rowindex = $(this).closest('tr').index(); console.debug('rowindex', rowindex); }); 

Note that you do not need a space between a and .showmore , because a .showmore will select any elements with the showmore class, which is a child of the binding.

In addition, .parent() is a method, so you need () after parent if you want to use .parent() .

Another suggestion is that instead of the multiple parent() method, you can use .closest ()

+15
source share

You can try:

 $(document).on('click', '.showMore', function(event) { var rowindex = $(this).closest('tr').index(); console.debug('rowindex', rowindex); }); 
+4
source share

you should use event delegation for this

 $(document).on('click',".showMore", function(event) { var rowindex = $(this).parents("tr").index(); console.debug('rowindex', rowindex); }); 

Event delegation allows you to attach one event listener to the parent element, which will be triggered for all children corresponding to the selector, regardless of whether these children exist now or are added in the future.

+3
source share

All Articles