Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 30008  / 10 Years ago, thu, march 27, 2014, 12:00:00

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);
});

More From » jquery

 Answers
44

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()


[#71751] Wednesday, March 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;