0

EDIT: the best explanation i could find to handle loop closure in js is Javascript infamous Loop issue?

so with my code it works as:

  a.onclick = function (url) {
            return function () {
                OnSearchResultClick(url);
            }
        }(urlStr);

POST: i am trying to dynamically build a list in js by iterating on a json array received from an ajax request.

scenario 1:

 for (var i = 1; i < results.length; i++) {
        //alert(results[i]['url']);
        var nameStr = results[i]['name'];
        var urlStr = results[i]['url'];

        var a = document.createElement("a");
        a.textContent = nameStr;
        a.id = nameStr;
        a.href = "#";
        a.onclick = function () {OnSearchResultClick(urlStr);};

in firebug i see the onclick event will call exactly that : OnSearchResultClick(urlStr) and so will take the last set value of urlStr, which means all a tags created this way call the function with the same argument.

scenario 2:

a.onclick = function () {OnSearchResultClick(results[i]['url']);}

even stranger, in firebug I get TypeError: results[i] is undefined

scenario 3: tried to pass urlStr.value, it is undefined

so i am wondering how to send not the variable but the string value inside the urlStr variable

I have been checking documentations on javascript passing arguments by value or reference but can't seems to make this work

any help would be appreciated

thanks

Community
  • 1
  • 1
crazyghandi
  • 49
  • 1
  • 10

0 Answers0