Javascript阻止脚本的其余部分

时间:2015-07-07 13:17:07

标签: javascript jquery datatables

我使用数据表,我想添加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文件并在每个页面上单独加载它们。

1 个答案:

答案 0 :(得分:0)

经过大量尝试不同的东西后,我终于设法解决了这个问题。我并不确切知道它是如何工作的,但这就是我所做的。

我将此添加到表选项的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;
} );