问题
I'm trying to add a ondragstart handler to my dynamically created image:
var image = new Image();
image.src = "https://www.filepicker.io/api/file/JhJKMtnRDW9uLYcnkRKW";
image.onload = function(event){
this.ondragstart = drag(event);
divImage.appendChild(this);
};
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
However, I get the error: Uncaught TypeError: Cannot call method 'setData' of undefined
I have tried this with a static image that I load via the dom and it works fine, but why doesn't my dynamically generated image work? For some reason, in the drag function, ev does not contain the dataTransfer object when it's a dynamically created image? Does anyone know why?
This is what I'm trying to do: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop except, I want to be able to dynamically create the image via javascript, and add the ondragstart handler to it.
Thanks,
回答1:
Because dynamically generated elements do not belong to the DOM on pageload, you need to addEventListener
to every new instance of your element, like this:
this.addEventListener('dragstart', function() {drag(ev)}, false);
I created a fiddle here that shows you it works (with some modifications to your code and some assumptions).
The img's are first loaded into the blue 'body' div, you will see this if you click the button quickly a couple of times.
This Stackoverflow post is strongly related to yours: Javascript ondrag, ondragstart, ondragend
EDIT: As it's stated in the post, if you want a cross-browser solution for dragging events, you're better off using a js framework.
来源:https://stackoverflow.com/questions/16296029/adding-ondragstart-handler-to-dynamically-created-images