如何使用jQuery/JavaScript模拟DataTables间的拖拽功能
Got it, let's walk through how to implement drag-and-drop between your two DataTables. I'll use jQuery UI for the drag/drop interactions since it simplifies handling events and visual feedback, but I'll also note a vanilla JS alternative if you prefer that route.
First, let's assume your second table has a similar structure to the one you provided—let's call it tableTargetFields for clarity. Here's the step-by-step breakdown:
Prerequisites
- Ensure you have jQuery and jQuery UI included in your project (we'll use their draggable/droppable utilities). If you're avoiding jQuery UI, skip to the vanilla JS section below.
- Make sure both tables are initialized as DataTables before applying drag/drop logic (wrap your code in
$(document).ready()or useDOMContentLoadedfor vanilla JS).
Step 1: Make Rows Draggable
Target the rows in your source table (tableListViewFields) that you want to drag. We'll use the drag-cue class as our selector:
$(document).ready(function() { // Initialize DataTables first const sourceTable = $('#tableListViewFields').DataTable(); const targetTable = $('#tableTargetFields').DataTable(); // Make source rows draggable $('#tableListViewFields .drag-cue').draggable({ helper: 'clone', // Drag a copy instead of moving the original immediately revert: 'invalid', // Snap back if dropped outside a valid zone cursor: 'move', start: function(event, ui) { // Optional visual feedback when dragging starts ui.helper.addClass('dragging'); } });
Step 2: Set Up the Drop Zone
Turn the target table's tbody into a droppable area that accepts dragged rows:
// Make target table's tbody a drop zone $('#tableTargetFields tbody').droppable({ accept: '.drag-cue', // Only accept rows with the drag-cue class hoverClass: 'drop-hover', // Highlight the zone when hovering over it drop: function(event, ui) { handleDrop(event, ui, $(this), sourceTable, targetTable); } }); });
Step 3: Handle Drop Logic
Create a function to manage adding the row to the target table, removing it from the source, and refreshing both DataTables:
function handleDrop(event, ui, dropTarget, sourceTable, targetTable) { // Extract data from the dragged row const draggedRow = ui.draggable; const rowName = draggedRow.data('name'); const rowIndex = draggedRow.data('index'); // Create a new row element for the target table const newRow = $(` <tr class="drag-cue" data-name="${rowName}" data-index="${rowIndex}"> <td class="no-border-right">${rowName}</td> </tr> `); // Add the row to the target table and remove from source dropTarget.append(newRow); draggedRow.remove(); // Refresh DataTables to reflect changes sourceTable.draw(); targetTable.draw(); // Optional: Add success animation newRow.addClass('dropped').delay(600).removeClass('dropped'); }
Step 4: Add CSS for Visual Feedback
Make the drag/drop experience more intuitive with some simple styling:
.dragging { opacity: 0.7; background-color: #f0f0f0; } .drop-hover { background-color: #e8f4f8; } .dropped { background-color: #d4edda; transition: background-color 0.3s ease; }
Vanilla JS Alternative (Brief Overview)
If you don't want to use jQuery UI, you can use the native HTML5 Drag and Drop API:
- Add
draggable="true"to yourdrag-cuerows - Listen for
dragstarton the source rows: store row data inevent.dataTransfer.setData() - Listen for
dragoveron the target tbody: callevent.preventDefault()to allow dropping - Listen for
dropon the target tbody: retrieve the stored data, create a new row, update the DOM, and refresh your DataTables withdraw().
内容的提问来源于stack exchange,提问作者Peter

