[英]How to get the class name of a dropped item with JavaScript?
I have few containers and few items. 我的容器很少,物品很少。 I want to drag an item into a container and get the class name of the dropped item.
我想将项目拖到容器中并获取已删除项目的类名称。
Getting a class name is very easy .className
but is not working 获取类名非常容易
.className
但不起作用
This is some code that I am working with (the places[i]
is part of a loop so I did not include the entire code for the sake of clarification): 这是我正在使用的一些代码(
places[i]
是循环的一部分,所以为了澄清,我没有包含整个代码):
places[i].addEventListener('drop', function(e){
console.log(this.childNodes[0].className );
});
This does not work, the error is "Cannot read property 'className' ". 这不起作用,错误是“无法读取属性'className'”。 I tried just
this.childNodes
and I get: 我试过这个
this.childNodes
,我得到:
[item: function]
0: div.coins.blue
....
className: "coins blue"
...
I did try this.childNodes['item']
logged function item() { [native code] }
. 我确实尝试过
this.childNodes['item']
记录的function item() { [native code] }
。 Don't know where to go from here 不知道从哪里开始
here is a the basic code http://jsbin.com/wadavuci/1/edit?js,console,output 这是一个基本代码http://jsbin.com/wadavuci/1/edit?js,console,output
Thanks 谢谢
When using drag-and-drop you must set manually set the data to transfer in the dragstart
event. 使用拖放时,必须手动设置要在
dragstart
事件中传输的数据。 The data is set using the setData()
member of the dataTransfer
object of the event: 使用事件的
dataTransfer
对象的setData()
成员设置数据:
for (var i=0; i<coins.length; i++) {
coins[i].addEventListener('dragstart', function(e){
e.dataTransfer.setData("text/plain", this.className);
});
}
Similarly, you must read the transferred data in the drop
event: 同样,您必须在
drop
事件中读取传输的数据:
for (var i=0; i<places.length; i++) {
places[i].addEventListener('drop', function(e){
console.log(e.dataTransfer.getData("text/plain"));
});
/* ... */
};
The Native HTML5 Drag and Drop article on http://www.html5rocks.com/ provides a nice walk through of how to handle drag-and-drop. http://www.html5rocks.com/上的Native HTML5 Drag and Drop文章提供了如何处理拖放的精彩步骤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.