最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get ID of draggable element - Stack Overflow

programmeradmin1浏览0评论

Is there a way in native HTML5 drag and drop to get the id of the element with the attribut draggable="true" ?

At first i thought it's standard that you get the id from the draggable container but actually it is always the id from the children element you start dragging on which is very annoying.

Here is an fiddle: /

I need the id from the div ('correctid') instead of the image.

Any help is appreciated. :)

Is there a way in native HTML5 drag and drop to get the id of the element with the attribut draggable="true" ?

At first i thought it's standard that you get the id from the draggable container but actually it is always the id from the children element you start dragging on which is very annoying.

Here is an fiddle: https://jsfiddle/chickberger/2ujhodeh/2/

I need the id from the div ('correctid') instead of the image.

Any help is appreciated. :)

Share Improve this question asked Feb 17, 2016 at 2:03 paperboypaperboy 2013 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can get a reference to that element by accessing the currentTarget property instead of the target property on the event object.

In your case, event.target was referring to the innermost element that was being targeted.

You want the currentTarget property since it refers to the element that the event listener is attached to (which would be the element with the ondragstart attribute).

Updated Example

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

The 'ev.target' is an image. You can fix this by using the parentNode:

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.parentNode.id);
    alert(ev.target.parentNode.id);
}
发布评论

评论列表(0)

  1. 暂无评论