简体   繁体   中英

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

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].addEventListener('drop', function(e){
  console.log(this.childNodes[0].className  );
});

This does not work, the error is "Cannot read property 'className' ". I tried just this.childNodes and I get:

[item: function]
  0: div.coins.blue
    ....
    className: "coins blue"
    ...

I did try this.childNodes['item'] logged 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

Thanks

When using drag-and-drop you must set manually set the data to transfer in the dragstart event. The data is set using the setData() member of the dataTransfer object of the event:

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:

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.

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