简体   繁体   中英

how to get the target id of the ondrop event?

I'm trying to do get the id of the target / destination of the dragged item. I have two containers, so I must get the ids of the one that has the dragged element.

Here is my code:

    <div id="div1" ondrop="drop(event, this)" ondragover="allowDrop(event)"></div>
 <div id="div2" 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" />

    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)
}

The result of this code returns drag1 instead of div1 or div2.

What am I missing?

ev.target.id in drop() is the reference to the destination item.

Try this code:

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

function drop(ev, target) {
    ev.preventDefault();
    alert(ev.target.id)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM