Div间元素双向拖拽迁移及动态数据捕获技术问题求助
Hey there! Let's fix your three key issues step by step and get your drag-and-drop setup working exactly as you need it.
1. Fix Batch Element Migration (Append, Not Swap)
Your current Parent() and Child() functions were moving the entire <div> elements instead of their child <span>s. To append all elements from one container to another (without swapping), we'll modify these functions to target the <span> elements directly and use appendTo():
function Parent() { // Move all spans from parent to child (append to end) $("#parent span").appendTo("#child"); // Update captured values after migration updateCapturedValues(); } function Child() { // Move all spans from child to parent (append to end) $("#child span").appendTo("#parent"); // Update captured values after migration updateCapturedValues(); }
2. Real-Time Data Capture
Your original code only captured values once when the page loaded. We'll create a reusable function to update the displayed values whenever elements are moved (either via drag-and-drop or batch buttons):
function updateCapturedValues() { // Capture child div spans and update display const childValues = $.map($("#child span"), elem => $(elem).text().trim()); $("#displayvalueschild").text(childValues.join("-")); // Capture parent div spans and update display const parentValues = $.map($("#parent span"), elem => $(elem).text().trim()); $("#displayvaluesparent").text(parentValues.join("-")); // Optional: Keep the parent array ready for database insertion window.parentDataArray = parentValues; }
We'll also call this function after the drop() event to update values when individual elements are dragged:
function drop(ev) { ev.preventDefault(); const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); // Update values after single drag updateCapturedValues(); }
3. Prepare Parent Data as Array for Database
The parentValues variable in updateCapturedValues() is already an array of the span texts. We can store it in a global variable (or pass it directly to an AJAX call) to send to your PHP backend for database insertion.
Example AJAX Call to Save Array to Database
function saveParentDataToDB() { $.ajax({ url: "your-save-script.php", // Replace with your PHP endpoint method: "POST", data: { parentData: window.parentDataArray }, success: function(response) { console.log("Data saved successfully:", response); }, error: function(xhr, status, error) { console.error("Error saving data:", error); } }); }
You can call this function on a button click or automatically after each migration, depending on your needs.
Full Modified Code
Style Code
.div-to-drag { width: 350px; height: 70px; padding: 10px; border: 1px solid #aaaaaa; overflow: scroll; } #parent { height: 100px; width: 300px; background: green; margin: 0 auto; overflow: scroll; } #child { height: 100px; width: 300px; background: blue; margin: 0 auto; overflow: scroll; }
HTML Code
Fixed duplicate #result divs to use correct display IDs:
<div id='parent' class='div-to-drag' ondrop='drop(event)' ondragover='allowDrop(event)'> <?php echo "<span id='div1parent' draggable='true' ondragstart='drag(event)'>First Parent<br></span>"; ?> <?php echo "<span id='div2parent' draggable='true' ondragstart='drag(event)'>Second Parent<br></span>"; ?> <?php echo "<span id='div3parent' draggable='true' ondragstart='drag(event)'>Third Parent<br></span>"; ?> </div> <br> <div id='child' class='div-to-drag' ondrop='drop(event)' ondragover='allowDrop(event)'> <?php echo "<span id='div1child' draggable='true' ondragstart='drag(event)'>First Child<br></span>"; ?> <?php echo "<span id='div2child' draggable='true' ondragstart='drag(event)'>Second Child<br></span>"; ?> <?php echo "<span id='div3child' draggable='true' ondragstart='drag(event)'>Third Child<br></span>"; ?> </div> <br> <div>Parent Values: <span id="displayvaluesparent"></span></div> <div>Child Values: <span id="displayvalueschild"></span></div> <br> <button type="button" onclick="Parent()"> Move From Parent to Child </button> <button type="button" onclick="Child()"> Move From Child to Parent </button> <!-- Optional button to save parent data to DB --> <button type="button" onclick="saveParentDataToDB()"> Save Parent Data to Database </button>
Script Code
function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); const data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); updateCapturedValues(); } function Parent() { $("#parent span").appendTo("#child"); updateCapturedValues(); } function Child() { $("#child span").appendTo("#parent"); updateCapturedValues(); } function updateCapturedValues() { // Capture and display child values const childValues = $.map($("#child span"), elem => $(elem).text().trim()); $("#displayvalueschild").text(childValues.join("-")); // Capture and display parent values, plus store as array const parentValues = $.map($("#parent span"), elem => $(elem).text().trim()); $("#displayvaluesparent").text(parentValues.join("-")); window.parentDataArray = parentValues; } function saveParentDataToDB() { $.ajax({ url: "your-save-script.php", method: "POST", data: { parentData: window.parentDataArray }, success: function(response) { alert("Data saved successfully!"); console.log("Response:", response); }, error: function(xhr, status, error) { alert("Failed to save data."); console.error("Error:", error); } }); } // Initialize values on page load $(document).ready(function() { updateCapturedValues(); });
Notes for Your PHP Backend
In your your-save-script.php, you can access the array via $_POST['parentData'] and insert it into your database. For example:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['parentData'])) { $parentData = $_POST['parentData']; // Sanitize data before inserting (important for security) $sanitizedData = array_map(function($item) { return htmlspecialchars(trim($item), ENT_QUOTES); }, $parentData); // Example: Insert into a database (replace with your DB logic) // $pdo = new PDO('mysql:host=your-host;dbname=your-db', 'user', 'pass'); // $stmt = $pdo->prepare("INSERT INTO your_table (value) VALUES (?)"); // foreach ($sanitizedData as $value) { // $stmt->execute([$value]); // } echo json_encode(["success" => true, "data" => $sanitizedData]); } else { echo json_encode(["success" => false, "message" => "Invalid request"]); } ?>
内容的提问来源于stack exchange,提问作者pjustindaryll

