获取可拖动元素的ID

问题描述:

在本机HTML5中是否有拖放方法可获取具有属性 draggable ="true" 的元素的ID?

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

起初,我认为从可拖动容器中获取ID是一种标准,但实际上,它总是从您开始拖动的children元素中获得的ID,这很烦人.

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.

这是一个小提琴: https://jsfiddle.net/chickberger/2ujhodeh/2/

我需要来自div的ID("correctid"),而不是图片.

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

感谢您的帮助.:)

您可以通过访问

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

在您的情况下, event.target 指的是被定位的最里面的元素.

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

您需要 currentTarget 属性,因为它引用事件侦听器所附加的元素(该元素是具有 ondragstart 属性的元素).

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

更新示例

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