Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过jQuery获取动态表中的行索引_Javascript_Jquery - Fatal编程技术网

Javascript 如何通过jQuery获取动态表中的行索引

Javascript 如何通过jQuery获取动态表中的行索引,javascript,jquery,Javascript,Jquery,我使用jquery在页面中动态创建表内容,如何获取这个动态表的行号索引?在下面的代码中,当我单击“显示更多”链接时,我在下面的代码中使用了索引函数,但它不起作用。如何解决这个问题?谢谢 $.getJSON(JsonURL, function(data){ $.each(data, function(index, item){ var obj = item; books.push(book)

我使用jquery在页面中动态创建表内容,如何获取这个动态表的行号索引?在下面的代码中,当我单击“显示更多”链接时,我在下面的代码中使用了索引函数,但它不起作用。如何解决这个问题?谢谢

 $.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);
    });
$.getJSON(JsonURL,
功能(数据){
$。每个(数据、功能(索引、项目){
var obj=项目;
书。推(书);
});
对于(var i=0;i您应该使用

事件委派允许您将单个事件侦听器附加到父元素,该事件侦听器将为与选择器匹配的所有子元素激发,无论这些子元素现在存在还是将来添加。

对于动态创建的元素,您需要使用

事件委派允许我们将单个事件侦听器附加到 父元素,将为与选择器匹配的所有子元素激发, 无论这些孩子现在存在还是将来被添加

请注意,
a
.showmore
之间不需要空格,因为
a.showmore
将选择具有类
showmore
的任何元素,该类是锚的子元素

另外,
.parent()
是一种方法,因此如果要使用
.parent()
,则需要在
parent
之后使用
.parent()

另一个建议是,您可以使用

而不是多个
父()方法,您可以尝试使用:

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