jQuery if 语句没有捕获#ID

jQuery if statement not catching #ID

我正在尝试编写一个简单的条件语句来检查元素的 ID,以便在将元素放到另一个元素上时识别它,但有些东西让我感到困惑...这是一个 JSFiddle:http://jsfiddle.net/4kvev05a/

HTML:

<div class="droppable" id="drop1">Drop region 1</div>
<div class="droppable" id="drop2">Drop region 2</div>

<div class="draggable" id="drag1">Drag 1</div>
<div class="draggable" id="drag2">Drag 2</div>

jQuery:

$( "#drag1" ).draggable();
$( "#drag2" ).draggable();

$( "#drop1" ).droppable({
  drop: function() {
    if ($(this).attr("id") == "drag1") {
        alert("drag1 was dropped on drop1");
      } else {
      alert("something else was dropped on drop1");
      }
    }
});
$( "#drop2" ).droppable({
  drop: function() {
    alert( "dropped on drop2" );
  }
});

当#drag1 或#drag2 被放到#drop1 上时,它运行 else{}...

drop event callback 中,this 指的是可放置元素(在本例中为 #drop1),这就是 if 条件语句不起作用的原因不出所料。

为了获得被删除元素的 id,在 drop event callback:

中使用 ui.draggable 访问该元素

Example Here

$("#drop1").droppable({
    drop: function (event, ui) {
        if (ui.draggable.attr("id") === "drag1") {
            // ...
        }
    }
});