Reputation: 323
I use jquery to dynamic create table content in page, how can I get the row number index of this dynamic table? In the following code, when I click the "show more" link, I use index function in following code, but it not work. How to solve this issue? 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);
});
Upvotes: 10
Views: 30207
Reputation: 38102
You need to use event delegation for dynamically created elements:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those 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);
});
Please note that you dont need a space between a
and .showmore
because a .showmore
will select any elements with class showmore
which is a child of an anchor.
Also, .parent()
is a method so you need ()
after parent
if you want to use .parent()
.
Another suggestion is that instead of multiple parent()
method, you can use .closest()
Upvotes: 16
Reputation: 25527
you should use event delegation for that
$(document).on('click',".showMore", function(event) {
var rowindex = $(this).parents("tr").index();
console.debug('rowindex', rowindex);
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
Upvotes: 4
Reputation: 152216
You can try with:
$(document).on('click', '.showMore', function(event) {
var rowindex = $(this).closest('tr').index();
console.debug('rowindex', rowindex);
});
Upvotes: 5