Javascript 阻止脚本的其余部分

Javascript blocking rest of script

我正在使用数据表,我想添加 colReorder 扩展。扩展工作正常,但它破坏了我的 js 文件中的很多 ajax 调用,我不知道为什么。

让我的 js 崩溃的代码

var colReorder = new $.fn.dataTable.ColReorder( testtable, {
    "aiOrder": [ 0, 1, 2, 3, 4, 5 ]
});

$('.reset-order-btn').click( function () {
    colReorder.fnReset();
    toastr["info"]("Columns reordered");
    return false;
} );

为什么会这样?

编辑:设法进一步缩小范围

这会影响我的 js:

var colReorder = new $.fn.dataTable.ColReorder( testtable, {
    "aiOrder": [ 0, 1, 2, 3, 4, 5 ]
});

编辑 2 进行澄清

到目前为止,我发现这两个功能不再起作用了。当我点击按钮时,它们不会启动。可能还有其他一些东西不起作用,因为我还没有测试所有这些东西。

$('#delete-all-selections').click(function(){
    $.ajax({
            type:"GET",
            url:"/TestData/selection-delete-all/",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                    var myNode = document.getElementById("selections-list");
                    myNode.innerHTML = '';
                    toastr["error"]("All selections deleted");
                    getSelection();
            }
    })
});

$('.selection-delete-btn').click(function(){
    var selectID = this.getAttribute('data');
    console.log(selectID);
    $.ajax({
            type:"GET",
            url:"/TestData/selection-delete/"+selectID,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                    JSON = $.parseJSON(data)
                    var myNode = document.getElementById("selections-list");
                    myNode = myNode.children[JSON.selectID]
                    console.log(myNode)
                    $(myNode).remove()
                    toastr["error"]("Selection deleted");
                    getSelection();
            }
    })
});

如果我删除 var colReorder 行,一切都会再次按预期运行。

编辑 3: 我在 js 控制台中发现了这个错误

Uncaught TypeError: Cannot read property '_colReorder' of undefined 

我发现当我加载另一个按钮停止工作的页面时,它会尝试 运行 此功能,这就是它崩溃的原因。我想我需要拆分我的 js 文件并在每个页面上单独加载它们。

经过多次尝试,我终于设法解决了这个问题。我不是很确定它是如何工作的,但这就是我所做的。

我将其添加到 table 选项的 initComplete 部分:

colReorder = new $.fn.dataTable.ColReorder( testtable, {
    "aiOrder": [ 0, 1, 2, 3, 4, 5 ]
});

如果没有 var,colReorder 将成为全局变量。 然后我可以使用它而不会阻止我的其他功能:

$('.reset-order-btn').click( function () {
    colReorder.fnReset();
    toastr["info"]("Columns reordered");
    return false;
} );