You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery/JavaScript:如何限制可放置容器仅接受一个拖拽项并支持替换?

Solution for jQuery UI Sortable Single-Item Target Containers with Auto-Return

Hey there! Let's fix those two requirements for your drag-and-drop setup. Here's how you can adjust your code to limit target containers to one item each, and automatically send the old item back to the word bank when a new one is dropped:

Step 1: Modify the Sortable Configuration

We'll use the receive event (triggered when an item is dropped into a connected container) to handle both the capacity limit and the auto-return logic. Here's the updated JavaScript:

$("#items1,#items2,#items3").sortable({
  connectWith: ".items", // Simplified since all containers share the .items class
  start: function (event, ui) {
    ui.item.toggleClass("highlight");
  },
  stop: function (event, ui) {
    ui.item.toggleClass("highlight");
  },
  receive: function(event, ui) {
    // Check if the target container is one of our limited target boxes
    if ($(this).hasClass("targetBoxes")) {
      // Get all items currently in the target container
      const targetItems = $(this).find(".list-inline-item");
      
      // If we now have more than 1 item, send the original one back to the word bank
      if (targetItems.length > 1) {
        // The first item is the old one - append it to items1 (word bank)
        targetItems.first().appendTo("#items1");
      }
    }
  }
}).disableSelection();

How This Works:

  • Capacity Limit: The receive event checks if the target container has the targetBoxes class. If it does, we count the number of items inside it. If the count exceeds 1, we trigger the auto-return logic.
  • Auto-Return Old Item: When a new item is dropped into a full target container, we grab the first (original) item in that container and append it back to #items1 (the word bank). The new item stays in the target container, effectively replacing the old one.

Additional Notes:

  • We simplified the connectWith value to ".items" because all three containers share that class—this keeps the code cleaner without changing functionality.
  • The appendTo("#items1") will add the old item to the end of the word bank. If you want it to go back to its exact original position, you'd need to track that position on drag start, but based on your requirements, appending to the word bank should suffice.

This should handle both of your requested features perfectly! Let me know if you need any tweaks.

内容的提问来源于stack exchange,提问作者sGlow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:56