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

咨询含if-else判断的jQuery Droppable拖拽代码是否可行

Fixing Your jQuery UI Droppable Logic

Hey there! No worries about your English at all—let's get this drag-and-drop behavior working exactly how you want it.

First, let's break down the issues in your current code:

  • You've got invalid syntax trying to wrap the drop callback in an if statement directly inside the droppable configuration object. The drop should be a function property of that object.
  • You missed the # in $('drag1')—jQuery needs that to select an element by ID.
  • To disable a draggable element correctly, you need to use the option method: draggable('option', 'disabled', true) instead of just passing disabled.

Since you already set accept: '#drag1', the drop event will only trigger when #drag1 is dropped onto #drop1. But if you wanted to add extra checks (or if you expand the accepted elements later), we can include conditional logic inside the drop function.

Here's the corrected code that does what you want:

$('#drop1').droppable({
  accept: '#drag1',
  drop: function(event, ui) {
    // Check if the dropped element is #drag1 (though accept already ensures this)
    if (ui.draggable.attr('id') === 'drag1') {
      $(this).css('background-color', 'green');
      $('#drag1').draggable('option', 'disabled', true);
    } else {
      $(this).css('background-color', 'red');
    }
  },
  // Optional: Reset background if the element is dragged away without dropping
  out: function() {
    $(this).css('background-color', '');
  }
});

Let me explain what's happening here:

  • The drop callback runs only when an accepted element is dropped. We double-check the ID just for clarity (you could skip this if you're sure accept is doing its job).
  • When #drag1 is dropped, we turn #drop1 green and disable the draggable element.
  • If for some reason a non-accepted element gets through (unlikely with your accept setting), it turns red.
  • The optional out handler resets the background color if the dragged element is pulled away without being dropped, which makes the behavior feel more intuitive.

If you wanted to handle cases where something else is dragged over (not just dropped), you could also use the over and out events to change the background as the element hovers.

内容的提问来源于stack exchange,提问作者Paul Tanné

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:01:50