获取已删除的元素ID而不是drop target id

Jas*_*son 7 javascript jquery html5 drag-and-drop

我对jQuery相当新,并且我试图将拖动的图像元素id附加到放置目标而不是图像元素本身或放置目标id.我正在使用html5原生DnD.到目前为止,我可以通过使用drag函数中的datatransfer方法和drop中的getdata函数发送其id来获取元素本身.每当我尝试从drop中调用该id时,它会获得drop target id而不是拖动的元素.

任何帮助将非常感激,因为我已经在网上彻底搜索,并找到了更多的方法来获得丢弃区域的目标ID.这是我当前代码小提琴的片段:

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

function dragStart(ev) {

ev.dataTransfer.setData('Text/html', ev.target.id); // sends the dragged images data.

//alert(ev.target.id); // alerts the correct id of the dragged image.

}


function drop(ev) {

ev.preventDefault();
var data = ev.dataTransfer.getData("text/html");//retrieves dropped images data.
ev.target.appendChild(document.getElementById(data));//this displays the dropped image.

//alert(ev.target.id); // alerts the id of the drop target(Want to get the dropped images id.)

//$("#mybillets").append("<span>"+ev.target.id+" </span>"); //appends the drop targets id(Want to append the dropped images id.)
}
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 14

drop方法中看起来像是ev事件对象,因此ev.target将引用放置项目的元素.

所以ev.target.id用来引用drop target id.

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

function drag(ev) {
    ev.dataTransfer.setData('Text/html', ev.target.id);
}

function drop(ev, target) {
    ev.preventDefault();
    console.log(target.id, ev.target.id)

    var data = ev.dataTransfer.getData("text/html");
    alert(data)
}
Run Code Online (Sandbox Code Playgroud)
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
Run Code Online (Sandbox Code Playgroud)
<div id="div1" ondrop="drop(event, this)" ondragover="allowDrop(event)"></div>
<br/>
<img id="drag1" src="//placehold.it/336X69/ff0000" draggable="true" ondragstart="drag(event)" width="336" height="69" />
Run Code Online (Sandbox Code Playgroud)

  • 我实际上是在尝试显示被拖动图像的 id 而不是放置目标,我编辑了我的代码以更好地说明我想要做什么。ev.target.id 指的是触发事件的元素,在 drop 事件的情况下,指的是图像被放入的区域。我想获取正在删除的图像的 ID。 (2认同)