Jquery表排序程序,排序只工作一次



当点击标签时,我会显示动态数据,这在表分类器中运行良好。单击表格标题就是对表格行进行排序。

我面临的问题是,在单击标签"一"和,然后单击标签"二",并尝试对第二个响应中的数据进行排序后,它从此停止工作。

这是我的代码:

$(document).on("click", ".candlespattern", function() {
    var clicked = $(this).attr("id");
    var datatoselect = '';
    if (clicked === 'one') {
        datatoselect = myjsonresponse1;
    } else if (clicked === 'two') {
        datatoselect = myjsonresponse2;
    }
    var html = "";
    html += '<thead><th class="thheaders">Symbol</th><th class="thheaders">Date</th></thead><tbody>';
    for (var e = 0; e < datatoselect.length; e++) {
        html += "<tr><td>" + datatoselect[e].name + "</td><td>" + datatoselect[e].date_time + "</td></tr>"
    }
    $("#candletable").html(html);
    $('#candletable').tablesorter({}).tablesorterPager({
        container: $(".pager"),
        size: 20
    });
    $("#candletable").trigger("update");
    $("#pager").show();
});

这是JSFiddle

好的,所以在研究了这个特定的插件之后,我发现了一个有用的例子。首先,您的问题很可能是每次点击该项时都会覆盖表thead,导致插件丢失一些引用。我建议你这样做:

由于thead对于两个响应都是相同的,所以不需要每次都动态添加它,我们可以将它放在HTML:中

<table id="candletable" class="table table-striped tablesorter">
    <!-- add the table head and an empty tbody -->
    <thead>
        <th class="thheaders">Symbol</th>
        <th class="thheaders">Date</th>
    </thead>
    <tbody>
    </tbody>
</table>

接下来,我们应该只初始化tablesorter一次,然后只更新数据:

$(document).ready(function() {    
    // initialize the table sorter on document.ready
    $('#candletable').tablesorter({}).tablesorterPager({
        container: $(".pager"),
        size: 20
    });
    $("#pager").hide();
});

最后,我们从点击处理程序中删除thead数据和初始化,并将创建的表行添加到tbody:

$(document).on("click", ".candlespattern", function() {
    var clicked = $(this).attr("id");
    var datatoselect = '';
    if (clicked === 'one') {
        datatoselect = myjsonresponse1;
    } else if (clicked === 'two') {
        datatoselect = myjsonresponse2;
    }
    // create the table rows from the response
    var html = ""; 
    for (var e = 0; e < datatoselect.length; e++) {
        html += "<tr><td>" + datatoselect[e].name + "</td><td>" + datatoselect[e].date_time + "</td></tr>"
    }
    // add the rows to table body
    $("#candletable tbody").html(html);
    // update the table
    $("#candletable").trigger("update");
    // show it
    $("#pager").show();
});

这是一个正在工作的FIDDLE

最新更新