Jquery table 排序器,排序只工作一次

Jquery table Sorter , sorting is working only one time

单击标签时,我会显示动态数据,这与 table 分拣机配合使用效果很好。单击 table headers 正在对 table 行进行排序。

我面临的问题是,在单击标签 "One" 和 然后 单击标签 "Two" 后,尝试对第二个标签的数据进行排序响应,它从这里开始停止工作。

这是我的代码:

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

Here is JSFiddle

好的,在研究了这个特定的插件之后,我发现了一个 useful example。 首先,您的问题很可能是您覆盖了 table 每次 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 数据和初始化,并将创建的 table 行添加到 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();
});

Here's a working FIDDLE