识别拖动的物品

时间:2018-06-04 13:30:56

标签: javascript

我(再一次)处理拖放项目,我(目前)无法解决以下问题。

值得关注的代码段是:

function allowDrop(ev) {ev.preventDefault();}

function drag(ev) {ev.dataTransfer.setData("text", ev.target.id);}

function drop(ev) {
    ev.preventDefault();

    // Find out the name of the DIV you are dropping this in to
    var prntId = ev.target.parentNode.id;

    var tgt = ev.dataTransfer.getData("text");

    alert ("ev.target.id = " + ev.target.id + "\n" + "prntId = " + prntId + "\n" + "tgt = " + tgt);

很简单,警报应该为我提供要删除的项目的ID,该项目的父DIV以及要删除的项目的ID(或者项目被拖动的DIV)。然而,这是我无法识别的最后一段数据。

我使用几乎完全相同的代码实现了这一点,但这次我有一个被拖放的东西。

如何识别可拖动项目的ID,或者来自它的父项(两者都可以)?

1 个答案:

答案 0 :(得分:0)

I tried to run your code and here is what I ended up with. Please click "Run code snippet" and drag'n'drop a link into the square.

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

document.getElementById('draggable_link').addEventListener('dragstart', drag);

// We have to add next 2 listeners to be able to "drop"
function dragover(e) {
  e.preventDefault();
}
function dragenter(e) {
  e.preventDefault();
}

function drop(ev) {
    ev.preventDefault();

    var prntId = ev.target.parentNode.id;
    var tgt = ev.dataTransfer.getData("text");

    alert("ev.target.id = " + ev.target.id + "\n" + "prntId = " + prntId + "\n" + "tgt = " + tgt);
}

document.getElementById('drop_zone').addEventListener('dragover', dragover);
document.getElementById('drop_zone').addEventListener('dragenter', dragenter);
document.getElementById('drop_zone').addEventListener('drop', drop);
#drop_zone {
  border: 1px solid black;
  width: 100px;
  height: 100px;
}
<div id="drop_zone_parent">
  <div id="drop_zone"></div>
</div>

<div id="drag_from_list">
  <a id="draggable_link" href="http://google.com">Drop me into the square</a>
</div>

Everything seems to be working right.

Please let me know if it helped. If not then please post a full version of your code to jsbin so I can debug it.