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

如何获取拖入droppable区域的每个draggable div的ID?

获取被拖拽元素ID并执行对应函数(jQuery UI)

问题核心

你当前代码的问题在于,$('#draggables').children().attr('id')只会返回所有可拖拽元素中第一个的ID,而非实际被拖拽的元素ID。要解决这个问题,需要利用jQuery UI提供的拖拽事件参数来定位目标元素。

解决方案

在droppable的drop回调中,通过第二个参数ui访问被拖拽的元素:ui.draggable就是当前被放下的元素,调用.attr('id')即可获取其ID,随后就能根据ID执行对应的函数。

修改后的完整代码

HTML

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
</head>
<body>
  <main>
    <section id="draggables">
      <div id="1" class="draggable">1</div>
      <div id="2" class="draggable">2</div>
      <div id="3" class="draggable">3</div>
      <div id="4" class="draggable">4</div>
    </section>
    <div id="droppable">
      <p>Drop Something Here</p>
    </div>
  </main>
</body>
</html>

CSS

body{
    background-color: #111;
    color: #555;
  }
  main{
    display: flex;
    gap: 40px;
  }
  #draggables{
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  .draggable{
    display: flex;
    align-items: center;
    justify-content: center;
    background: #151515;
    border: 1px solid #222;
    width: 100px;
    height: 100px;
    cursor: move;
  }
  #droppable{
    display: flex;
    align-items: center;
    justify-content: center;
    background: #090909;
    border: 1px solid #222;
    width: 200px;
    height: 200px;
  }

JavaScript

$('#draggables').children().draggable({
    revert: "invalid"
})
$('#droppable').droppable({
    accept: $('#draggables').children(),
    drop: function(event, ui){
        // 获取被拖拽元素的ID
        const draggedId = ui.draggable.attr('id');
        alert(`被拖拽的元素ID:${draggedId}`);
        
        // 根据ID执行对应函数
        switch(draggedId){
            case '1':
                handleDrag1();
                break;
            case '2':
                handleDrag2();
                break;
            case '3':
                handleDrag3();
                break;
            case '4':
                handleDrag4();
                break;
        }
    }
})

// 自定义对应ID的处理函数
function handleDrag1(){
    console.log("处理ID为1的元素拖拽");
}
function handleDrag2(){
    console.log("处理ID为2的元素拖拽");
}
function handleDrag3(){
    console.log("处理ID为3的元素拖拽");
}
function handleDrag4(){
    console.log("处理ID为4的元素拖拽");
}

关键说明

  • ui.draggable是jQuery UI在drop事件中传递的核心对象,精准指向当前完成拖拽动作的元素。
  • 除了switch语句,也可以用对象映射的方式优化函数调用,比如:
    const dragHandlers = {
      '1': handleDrag1,
      '2': handleDrag2,
      '3': handleDrag3,
      '4': handleDrag4
    }
    dragHandlers[draggedId]?.();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:50:28