使用Ajax HTML输出的分页正在破碎

时间:2015-12-09 10:22:29

标签: javascript jquery html ajax

我正在添加屏幕截图,您可以解决问题。

当我单击下一个按钮时,第一行,第一列被更改,但第一行第二列未更改,代替第一行,第三列被替换。为什么不替换第一行 - 第二列?

jQuery('document').ready(function() {
    jQuery('.next-page').click(
        function( event ) {
            event.preventDefault();

            url = jQuery(this).attr('href');
            jQuery.ajax({
                url: url,
                context: document.body
            }).done(function(data) {
                console.log(data);

                //console.log(data.nextlink);
                //console.log(data.previousLink);
                //console.log(jQuery('.report-table>tbody>tr>td').is('td'));

                posts = data.rows;
                jQuery('.report-table>tbody>tr>td:eq(0)').replaceWith(posts[0][0]);
                jQuery('.report-table>tbody>tr>td:eq(1)').replaceWith(posts[0][1]);
                for( i = 0; i < posts.length; i++ ) {
                    for( j = 0; j < 7; j++ ) {
                        //jQuery('.report-table>tbody>tr>td:eq(' + j + ')').replaceWith(posts[i][j]);

                        //console.log(jQuery('.report-table>tbody>tr>td:eq(' + j + ')').is('td'));
                        //console.log( i + "  => " + j + "  =>  " + posts[i][j] );
                    }
                }
            });
        });
});

点击下一个按钮之前

Enter image description here

点击下一个按钮后

Enter image description here

1 个答案:

答案 0 :(得分:1)

.replaceWith()方法删除与已删除节点关联的所有数据和事件处理程序。这就是为什么当你替换第一行第一列时,实际上整个 td 被替换为posts[0][0]。因此,当您尝试替换第二列时,它会将第三列中的 td 替换为posts[0][1],因为现在只剩下两列了。

所以为此而不是.replaceWith()使用.html()来替换内容,如下所示:

jQuery('document').ready(function(){
jQuery('.next-page').click(
    function( event ){
        event.preventDefault();

        url = jQuery(this).attr('href');
        jQuery.ajax({
            url: url,
            context: document.body
        }).done(function( data ){
            console.log( data );

            //console.log( data.nextlink );
            //console.log( data.previousLink );
            //console.log(jQuery('.report-table>tbody>tr>td').is('td'));
            posts = data.rows;
            jQuery('.report-table>tbody>tr>td:eq(0)').html(posts[0][0]);
            jQuery('.report-table>tbody>tr>td:eq(1)').html(posts[0][1]);
            for( i = 0; i < posts.length; i++ ){
                for( j = 0; j < 7; j++ ){
                   jQuery('.report-table tbody tr:eq('+ i +') td:eq(' + j + ')').html(posts[i][j]);
                    //jQuery('.report-table>tbody>tr>td:eq(' + j + ')').replaceWith(posts[i][j]);

                     //console.log(jQuery('.report-table>tbody>tr>td:eq(' + j + ')').is('td'));
                    //console.log( i + "  => " + j + "  =>  " + posts[i][j] );
                }
            }
        });

    });
});

它将根据您的需要替换内容。

为了使代码适用于每一行,请将tr:eq('+ yourRowIndex +')放在行中,并使用td

相关问题