jQuery在拖放时替换表格单元格

时间:2014-09-07 16:36:38

标签: jquery html cells

小提琴:http://jsfiddle.net/macbeth3n1/5sdzsL3d/3/

将单元格(div)拖动到droppable(td)时,我需要将单元格替换和/或附加到新位置。但是在追加时,div不会位于我想要的屏幕上(与之前的数据相同),而在替换时,它完全消失。请参阅小提琴代码。救命!!

<table>
  <tr>
    <td class="drop" id="tdClass1">
      <div class="empty"></div>
      <input type="hidden" id="input1" />
    </td>
    <td class="drop" id="tdClass2">
        <div class="drag">Class 2</div>
        <input type="hidden" id="input2" />
    </td>
  </tr>
  <tr>
    <td class="drop" id="tdClass3">
        <div class="drag">Class 3</div>
        <input type="hidden" id="input3" />
    </td>
    <td class="drop" id="tdClass4">
        <div class="empty"></div>
        <input type="hidden" id="input4" />
    </td>        
  </tr>            
</table>

$(document).ready(function () {
  $('.drag').draggable ({
    cursor: "move",
    appendTo: "body",
    revert: "invalid",
    opacity: 0.5
  });

  $('.drop').droppable({
    accept: ".drag",
    tolerance: "pointer",
    snap: ".drop",

    drop: function (event, ui) {

        ui.draggable.position({
            of: $(this),
            my: 'left top',
            at: 'left top'
        });

        ui.draggable.draggable('option', 'revert', 'invalid');

        var parentTd=$(ui.draggable).closest('td');
        var parentDiv=$(ui.draggable).closest('div');
        var thisDiv = $(this).find('div');
        var emptyDiv=$('<div class="empty"></div>');

        alert ("thisTdId=" + $(this).attr('id') + 
               ", parentTdId=" + parentTd.attr('id'));

        thisDiv.replaceWith(ui.draggable);
        parentDiv.append(emptyDiv);
    }
  });
});

1 个答案:

答案 0 :(得分:0)

这是你想要实现的目标吗?

$(document).ready(function () {

    $('.drag').draggable ({
        cursor: "move",
        appendTo: "body",
        revert: "invalid",
        opacity: 0.5
    });

    $('.drop').droppable({
        accept: ".drag",
        tolerance: "pointer",
        snap: ".drop",

        drop: function (event, ui) {
            console.log(event, ui);
            $(this).append(ui.draggable);
            ui.draggable.css({top:0, left:0});
        }
    });
});