简体   繁体   中英

How I can pass argument out of the loop in javascript

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.

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);

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);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM