Noel Proulx
Noel Proulx

Reputation: 25

Difficulty developing unique dynamic onclick events in Javascript

I am working with a decent sized set of data relating to objects on the page and some objects need links applied to them onclick. The link to connect to is part of the dataset and I build a string for the link with the variable linkTarget and apply it like so.

 if (dataTag[i][3]==true){

    if(prepend==undefined || prepend=="undefined"){                         
        var linkTarget=ResultsJSON["targetUrl"];
        ele.onclick = function(){
            window.open(linkTarget);
        };
    } else {
        var linkTarget=prepend+ResultsJSON["targetUrl"];
        ele.onclick = function(){
            window.open(linkTarget);
        };
    }

ele refers to an element picked up with getElementByID. Now I am going through quite a few objects and the problem I have is the onclick for every object is the last value of linkTarget. This is all contained in a function and link target is a local variable so I have no idea why. I have tried using an array with something like

ele.onclick=function(){window.open(linkTarget[linkTarget.length-1]);};

and even

ele.onclick=function(){window.open(linkTarget.valueOf());};

with the same results. I am at a loss now and would appreciate any help.

Upvotes: 1

Views: 185

Answers (2)

gilly3
gilly3

Reputation: 91497

Use Array.forEach() to iterate your data and watch your troubles melt away.

dataTag.forEach(function (item) {
    if (item[3]==true) {
        var linkTarget = "";
        if (prepend==undefined || prepend=="undefined") {
            linkTarget = prepend;
        }
        linkTarget += ResultsJSON.targetUrl;
        ele.onclick = function () {
            window.open(linkTarget);
        };
    }
});

See this compatibility note for using Array.forEach() in older browsers.

Upvotes: 3

Ry-
Ry-

Reputation: 224913

You're in a loop — therefore, you need to put your things-to-be-executed in another function, like so:

 if(dataTag[i][3]) {
    if(prepend) {   
        (function(linkTarget) {
            ele.onclick = function() {
                window.open(linkTarget);
            };
        })(ResultsJSON.targetUrl);
    } else {
        (function(linkTarget) {
            ele.onclick = function() {
                window.open(linkTarget);
            };
        })(ResultsJSON.targetUrl);
    }

I also made some general corrections.

Upvotes: 1

Related Questions