jQuery if语句没有捕获#ID

时间:2015-03-11 01:36:37

标签: javascript jquery if-statement drag-and-drop

我试图编写一个简单的条件语句来检查一个元素的ID,以便在被放到另一个元素上时识别它并且有什么东西让我失望......这里是JSFiddle:{{ 3}}

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 {} ...

1 个答案:

答案 0 :(得分:0)

drop event callback内,this引用了droppable元素(在本例中为#drop1),这就是if条件语句未按预期工作的原因

要获取已删除元素的id,请使用drop event callback中的ui.draggable访问该元素:

Example Here

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