0

I have this code below:

for (var index in mv.exifImages) {
        var p = document.createElement("p");
        var oText = document.createTextNode("link" + index);
        p.appendChild(oText);
        var info = mv.exifImages[index];
        p.onclick = function() {
            mv.openNewWindow(info);
        };
        ele.appendChild(p);
}

I want to create paragraph elements and when I click on them open a new window with correct array content. But I am anable to biuld different links. All my paragraphs open a new window with the array contents at the last index. Is there a trick around this?

Jacob
  • 3,580
  • 22
  • 82
  • 146

2 Answers2

2

I think this should work:

for (var index in mv.exifImages) {
        var p = document.createElement("p");
        var oText = document.createTextNode("link" + index);
        p.setAttribute("indexAttr",index);
        p.appendChild(oText);
        p.onclick = function() {
            mv.openNewWindow(mv.exifImages[this.getAttribute("indexAttr")]);
        };
        ele.appendChild(p);
}
haitaka
  • 1,832
  • 12
  • 21
0

The following works...

for (var index in mv.exifImages) {
        var p = document.createElement("p");
        var oText = document.createTextNode("link" + index);
        p.appendChild(oText);
        var info = mv.exifImages[index];
        p.onclick = openNew(info);
        ele.appendChild(p);
}

function openNew(a) {
    return function() {
        mv.openNewWindow(a);
    }
}
olan
  • 3,568
  • 5
  • 24
  • 30