【问题标题】:Drag and drop not working after adding new row添加新行后拖放不起作用
【发布时间】:2012-09-28 07:55:34
【问题描述】:

我正在使用jquery.tablednd.0.7.min.js 拖放表格行。当我在表中动态添加新行(即使用 javascript 添加行)时,新行没有拖放。可以拖动表格中已经存在的其他行。

我认为这个新行没有与 jQuery 拖放代码同步。

我正在添加新行,例如 this

This是jquery dragnDrop文件代码。

在页面加载时,我使用此代码将此功能分配给表

$(document).ready(function() {
    $("#tableId").tableDnD({
        onDragClass : "myDragClass",
        onDrop : function(table, row) {

        },
        onDragStart : function(table, row) {
            console.log("drag start");
        }
    });
});

【问题讨论】:

  • 请分享一些代码或jsfiddle。
  • 这是因为事件在页面加载时附加到行,因此在此之后追加的新行将不会绑定到拖放功能。您需要将delegate()on() 与委托选择器一起使用来实现此目的。如果您发布代码,我可以告诉您确切的方法。
  • @RoryMcCrossan。是的,您是对的,事件附加到页面加载的行。请告诉我如何使用 delegate()
  • @imrantariq 在下面看到我的回答

标签: javascript jquery drag-and-drop


【解决方案1】:

只需使用$("#tableId").tableDnDUpdate()

来自文档:

Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells). This is useful if you have updated the table rows using Ajax and you want to make the table draggable again. The table maintains the original configuration (so you don't have to specify it again).

【讨论】:

  • 这是正确的答案 - 正如指出的其他答案将导致分拣机的双重绑定。
【解决方案2】:

您还没有显示附加行的代码,这是您需要重新绑定 tableDnD 相关事件的地方,但它看起来像这样:

$(document).ready(function() {
    //on load
    addTableDnD();

    //appending a row
    $(".add-row").click(function() {
        $("<tr />").appendTo("#tableId");
        addTableDnD(); // re-attach events to pick up the new row.
    });
});

function addTableDnD() {
    $("#tableId").tableDnD({
        onDragClass : "myDragClass",
        onDrop : function(table, row) {

        },
        onDragStart : function(table, row) {
            console.log("drag start");
        }
    });
}

【讨论】:

  • 它可以工作,但是拖动事件两次附加到已经存在的行,如果添加了另一行,则此事件附加到它们三次。担心:(
【解决方案3】:

就这么简单:

$("#tableId").tableDnDUpdate()

添加新行之后。

【讨论】:

    【解决方案4】:

    请试试这个:

    function sample()
    {
            $("#tableId").tableDnD({
                onDragClass : "myDragClass",
                onDrop : function(table, row) {
    
                },
                onDragStart : function(table, row) {
                    console.log("drag start");
                }
            });
    
    }
    

    在正文 onload 中调用 sample() 函数,并在每个新行进入时再次调用 sample() 函数。

    注意:为避免出现两次问题,请尝试在 jquery 中使用“live”功能

    【讨论】:

    • 它可以工作,但拖动事件两次附加到现有行,如果添加另一行,则此事件附加三次。担心:(
    • live 可以与事件一起使用。请举个例子
    • 请查看我的代码并告诉我将这个 live() 放在哪里。
    【解决方案5】:

    如果新添加的行 tr 与现有行具有相同的 id,tablednd 可能无法使其可拖动。

    【讨论】:

      【解决方案6】:
      $("#table_id").tableDnDUpdate();
      

      我用这个解决了同样的问题

      【讨论】:

        猜你喜欢
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-10
        • 2015-08-10
        • 2018-06-16
        • 1970-01-01
        相关资源
        最近更新 更多