adding ondragstart handler to dynamically created images

巧了我就是萌 提交于 2021-02-19 08:00:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!