javascript
  • dom
  • 2017-01-12 2 views 1 likes 
    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); 
        } 
    } 
    

    수동 ID (965) 대신 동적 ID 인수 this.unorderListLi[l].addEventListener('click', function() { ajaxJsonFetchPost(this.persons[person]['id']); }, false);을 전달하고 싶습니다. 그러나 그것은 루프에서 벗어났다. 아무도 실제 프로세스가 무엇인지 말해 줄 수 있습니까? 감사합니다. .자바 스크립트의 루프에서 인수를 전달할 수있는 방법

    답변

    0

    이미 클릭 핸들러가 연결된 요소의 일부로 저장된 ID가 있습니다. 각 사람의 li 요소는 이벤트 리스너를 원한다면

    this.unorderListLi[l].addEventListener('click', function() { 
        var idAttr = this.id; 
        ajaxJsonFetchPost(idAttr.split('aid')[1]); 
    }, false); 
    
    +0

    감사합니다 @Sushanth - 매력처럼 작동합니다. –

    +0

    @ sumum 당신은 환영합니다 :) –

    0

    당신이 요소에 직접 eventListener를 부착하고 있기 때문에, 당신은해야 당신의 ID이 들어있는 Event.target 속성 아래에있는 요소 자체의 속성에 액세스 할 수 있습니다.

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

    , 당신은 중첩 루프를해야합니다. personl 앞에 var을 사용하십시오. 그렇지 않으면 전역 변수를 작성하고 있습니다! jsonFetch() 안에 persons 대신 this.persons을 사용해야합니다.

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

    그 반환은 항상 마지막 id.6 –

    관련 문제