2017-11-02 2 views
-1

この結果、最後の要素はonclick関数を持ちます。他には何もない。私はあなたが(console.log(JSON.stringify(snapshot.val(),undefined,2)))の例を投稿してください可能性があり、どのように見えるかsnapshot.val()興味...javascriptループover .onclickとクエリ

function waitForLoad(id, callback){ 
    var timer = setInterval(function(){ 
     if(document.getElementById(id)){ 
      clearInterval(timer); 
      callback(); 
     } 
    }, 100); 
} 
// to skip the LocationSet and LocationName, because we want to reuse our old Location 
ref = new Firebase("https://iplus1app.firebaseio.com/"); 
userLocs = ref.child("users/{{ user.username }}/locations"); 
// create the button function to redirect for each Location that exists 
userLocs.once("value", function(snapshot) { 
    var keys = Object.keys(snapshot.val()) 
    for (i = 0; i < snapshot.numChildren(); i++) { 
     var locationKey = keys[i] 
     //var locationKey = Object.keys(snapshot.val()[keys[i]]) 
     var nickName = snapshot.val()[locationKey]['name'] 
     locLat = snapshot.val()[locationKey]['position']['lat'] 
     locLng = snapshot.val()[locationKey]['position']['lng'] 
     locNick = snapshot.val()[locationKey]['name'] 
     waitForLoad(nickName, function(){ 
       document.getElementById(nickName).onclick = (function(i) { 
        return function (i) { 
         tempRef = ref.child("users/{{ user.username }}/temp_location"); 
         tempRef.set({ 
          position: { 
           lat: locLat, 
           lng: locLng 
          }, 
          name: locNick    
         }) 
         location.href = "{% url 'tutorLocationActivities' %}"; 
        } 
       })(i); 
     });   
    } 
}) 
+0

は、スタックオーバーフローへようこそ!あなたがループのために、あなたはおそらくこのような何かをするためのもので正しく閉鎖を設定していないように見えます

[ツアー](https://stackoverflow.com/tour)にアクセスし、質問を編集してHTMLも表示してください。 –

答えて

0

を は、私が(で私を包むことにより、以前の回答を追跡しようとした)が、それは何もしていないようでした?

他のコードではhtml要素が生成されていて、他のコードが要素を作成するのを待っていますか?

は、私はあなたが何jQueryの(document.ready)を持っていない場合、あなたはイベントリスナーを追加したい要素を単に</body>タグの前にスクリプトを追加したり、defer属性(仮定を使用することができ、waitForLoad必要とする理由はわからないに静的であり、 )。

var i;//your for loop creates a global variable called i 
for (i = 0; i < snapshot.numChildren(); i++) { 
    waitForLoad(
    snapshot.val()[keys[i]]['name'] 
    ,(function(index){ 
     //create closure variables based on index 
     var locationKey = keys[index] 
     ,nickName = snapshot.val()[locationKey]['name'] 
     ,locLat = snapshot.val()[locationKey]['position']['lat'] 
     ,locLng = snapshot.val()[locationKey]['position']['lng'] 
     ,locNick = snapshot.val()[locationKey]['name']; 
     return function(){ 
     document.getElementById(nickName).onclick = 
      function (event) { 
      tempRef = ref.child("users/{{ user.username }}/temp_location"); 
      tempRef.set(
       { 
       position: { 
        lat: locLat, 
        lng: locLng 
       }, 
       name: locNick    
       } 
      ); 
      location.href = "{% url 'tutorLocationActivities' %}"; 
      } 
     ; 
     } 
    }(i)) 
); 
}