1
this.jsonFetch = function() {
    for (person in this.persons) {
        console.log(person, '= ', this.persons[person]['title']);
        this.unorderList.innerHTML += "<li><a id='aid" + this.persons[person]['id'] + "'href='#' >" + this.persons[person]['title']['rendered'] + "</a></li>";

    }
    this.unorderListLi = document.getElementById("ul").getElementsByTagName("a");
    for ( l = 0; l <= this.unorderListLi.length; l++ ) {
        this.unorderListLi[l].addEventListener('click', function() { ajaxJsonFetchPost(965); }, false);
    }
}

I want to pass dynamic id argument this.unorderListLi[l].addEventListener('click', function() { ajaxJsonFetchPost(this.persons[person]['id']); }, false); instead of manual id (965). but it is out of the loop. Can anyone tell me what is the actual process? Thanks.

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
sumanta.k
  • 321
  • 3
  • 18

3 Answers3

0

Since you are attaching the eventListener directly to the element, then you can access the attribute of the element itself under the Event.target attribute which should contains your id.

this.unorderListLi[l].addEventListener('click', 
    function(e) { 
      ajaxJsonFetchPost(e.target.getAttribute('id').slice(3)); // slice(3) to pick the number after "aid" string in id
    }, false);
DJ.
  • 6,212
  • 1
  • 28
  • 44
0

You already have the id stored as part of the element to which the click handler is associated.

this.unorderListLi[l].addEventListener('click', function() {
  var idAttr = this.id;
  ajaxJsonFetchPost(idAttr.split('aid')[1]);
}, false);
Sushanth --
  • 53,795
  • 7
  • 57
  • 95
0

If you want each person's li elements to have event listeners, you need to nest the loops. Also use var in front of person and l, otherwise you are making global variables! Make sure to use this.persons instead of persons inside jsonFetch().

this.jsonFetch = function() {
    for (var person in this.persons) {
        console.log(person, '= ', this.persons[person]['title']);
        this.unorderList.innerHTML += "<li><a id='aid" + this.persons[person]['id'] + "'href='#' >" + this.persons[person]['title']['rendered'] + "</a></li>";

        this.unorderListLi = document.getElementById("ul").getElementsByTagName("a");
        for (var l = 0; l <= this.unorderListLi.length; l++ ) {
            addEvt(this.unorderListLi[l], this.persons[person]['id']);
        }
    }
}

function addEvt(obj, id) {
    obj.addEventListener('click', function() {
        ajaxJsonFetchPost(id);
    }, false);
}
dodov
  • 4,065
  • 3
  • 25
  • 44