如何检测jQuery UI Sortable可排序元素的来源表格
解决方案:区分同表/跨表拖拽并检测来源表格
要实现同表拖拽后的来源检测,核心是在拖拽起始阶段记录元素所属的原始表格,再结合jQuery UI Sortable的事件区分场景:
实现步骤
- 在拖拽开始的
start事件中,保存拖拽元素所属的原始表格ID - 同表拖拽会触发
update事件,跨表拖拽会触发receive事件,在这两个事件中读取存储的来源ID,即可完成检测
修改后的完整代码
JavaScript 部分
$("#peopleTable1 tbody").sortable({ connectWith: "#peopleTable2 tbody", helper: function(e, tr) { const $originals = tr.children(); const $helper = tr.clone(); $helper.children().each(function(index) { $(this).width($originals.eq(index).width()); }); return $helper; }, start: function(e, ui) { // 存储拖拽元素的原始来源表格ID ui.item.data('sourceTable', ui.item.closest('table').attr('id')); }, update: function(e, ui) { // 同表拖拽触发:来源与当前表格一致 const sourceTable = ui.item.data('sourceTable'); console.log(`同表拖拽,来源表格:${sourceTable}`); }, receive: function(e, ui) { // 跨表拖拽触发:来源是另一个表格 const sourceTable = ui.item.data('sourceTable'); const currentTable = $(this).closest('table').attr('id'); console.log(`跨表拖拽,来源:${sourceTable} → 目标:${currentTable}`); }, axis: "xy", }); $("#peopleTable2 tbody").sortable({ connectWith: "#peopleTable1 tbody", helper: function(e, tr) { const $originals = tr.children(); const $helper = tr.clone(); $helper.children().each(function(index) { $(this).width($originals.eq(index).width()); }); return $helper; }, start: function(e, ui) { ui.item.data('sourceTable', ui.item.closest('table').attr('id')); }, update: function(e, ui) { const sourceTable = ui.item.data('sourceTable'); console.log(`同表拖拽,来源表格:${sourceTable}`); }, receive: function(e, ui) { const sourceTable = ui.item.data('sourceTable'); const currentTable = $(this).closest('table').attr('id'); console.log(`跨表拖拽,来源:${sourceTable} → 目标:${currentTable}`); }, axis: "xy", });
HTML 部分
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <table id="peopleTable1"> <thead class="thead-acu"> <tr> <th class="col-30p">Name</th> <th class="col-35p">Age</th> <th class="col">Sex</th> </tr> </thead> <tbody> <tr> <td>Peter</td> <td>13</td> <td>Boy</td> </tr> <tr> <td>David</td> <td>20</td> <td>Boy</td> </tr> <tr> <td>Martha</td> <td>40</td> <td>Girl</td> </tr> </tbody> </table> <table id="peopleTable2"> <thead class="thead-acu"> <tr> <th class="col-30p">Name</th> <th class="col-35p">Age</th> <th class="col">Sex</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>7</td> <td>Boy</td> </tr> <tr> <td>Laura</td> <td>27</td> <td>Girl</td> </tr> <tr> <td>ELisabeth</td> <td>73</td> <td>Girl</td> </tr> </tbody> </table>
关键逻辑说明
start事件记录来源:利用ui.item.closest('table')找到拖拽元素所属的原始表格,把ID存在元素的data属性里,避免全局变量污染update事件处理同表拖拽:当元素在同一个表格内调整顺序时,update事件触发,此时读取存储的来源ID,就能确认是同表操作receive事件处理跨表拖拽:跨表拖拽时receive事件触发,对比来源ID和当前表格ID,就能明确拖拽的方向
这样不管是同表还是跨表拖拽,都能精准检测到元素的来源表格。
内容的提问来源于stack exchange,提问作者user23454796
相关产品推荐
相关产品推荐

