0

I want to create more then one image in a for-loop. It works fine, except that every Image should get a dbclick eventlistener. This is also not the problem.

In the eventlistener, I call a function. This function gets some parameters (e.g. the id of the image).

When I start an alert, I get always the same id.

My code :

function loadImageAttribute(imageid,link) {
    var doc = document.getElementById("iframe_editor").contentWindow.document;  
        alert(imageid); // --> Always get the last id of the last image
        openWindow('windowimagechange');
    }

function insertImage() {
    for (var i = 0; i < list.files.length; i++) {
        var file = list.files[i];
        if ('name' in file) {
            txt += "name: " + file.name + "<br>";
        }
        if ('size' in file) {
            txt += "size: " + file.size + " bytes <br>";
        }
        document.getElementById("counterImage").value = parseInt(document.getElementById("counterImage").value)+1;
        var range= sel.getRangeAt(0);myParent=document.getElementById("iframe_editor").contentWindow.document.body;
        var img=document.createElement("img");
        img.src = "./fileuploads/"+file.name;
        img.id = "imgid"+document.getElementById("counterImage").value;
        myParent.appendChild(img);
        range.insertNode(img);
        doc.body.appendChild(p);
        img.addEventListener( 'dblclick', function(){
            loadImageAttribute(img.id,'');
        },img.id);
    }
}

When I check the eventlistener in the debug mode, I can see that als eventlistener get the right id.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Stefan Gum
  • 67
  • 5
  • 2
    In your case, use `this.id` instead of `img.id` in the event handler. Also, passing `img.id` as third argument to `addEventListener` doesn't make sense. – Felix Kling Feb 17 '16 at 21:31
  • why i have to use this.id? thx this was the mistake – Stefan Gum Feb 17 '16 at 21:32
  • Because `img` will always refer to the value of the last iteration (as you have noticed and as explained in the other question). `this` on the other hand will always refer to the element the handler is bound to. – Felix Kling Feb 17 '16 at 21:33
  • thx for the quick answer – Stefan Gum Feb 17 '16 at 21:35

0 Answers0