2016-03-12 21 views
0

我想動態創建元素並向它們添加事件監聽器。下面是一些代碼:獲取動態加載的整數變量的值

var marks = { 
    list:[{ 
    selected: "content", 
    url: "http://youtube.com/feed/subscriptions", 
    trait: "id" 
    },{ 
    selected: "js-streams streams items", 
    url: "http://twitch.tv/directory/following", 
    trait: "class" 
    }] 
}; 

var l = marks.list.length; 

var web = "<webview src='https://youtube.com/feed/subscriptions' preload='preload.js' disablewebsecurity></webview>";  

for(var i = 0; i < l; i++){ 
    var webadd = "<webview id=web" + i + " src=" + marks.list[i].url + " preload='preload.js' disablewebsecurity></webview>"; 
    $('#canvas1').append(webadd); 

    document.getElementById("web" + (i)).addEventListener("dom-ready", function() { 
     console.log("nice" + (i)); // <-- This line most likely needs changing 
    }); 
} 

現在,我能得到我的元素和各個事件偵聽器,但是當涉及到控制檯日誌,它打印出"nice2"兩次。有沒有辦法讓這條線獲得var i的值作爲一個整數而不是i本身?理想情況下,我希望它打印出nice0nice1。有任何想法嗎?謝謝。

回答

1

你最好使用foreach循環。這樣你可以有一個關閉並保持你的上下文。也讀得更好。

mark.list.forEach(function(item, i){ 
    var webadd = "<webview id=web" + i + " src=" + item.url + " preload='preload.js' disablewebsecurity></webview>"; 
    $('#canvas1').append(webadd); 

    document.getElementById("web" + i).addEventListener("dom-ready", function() { 
     console.log("nice" + i); // <-- 
    }); 
}) 
+0

謝謝,這個效果很好! – Kragalon

1

您需要創建您的事件偵聽器,並結合當前i給它一個額外的功能:

document.getElementById("web" + (i)).addEventListener("dom-ready", (function(n) { 
    return function() { 
     console.log("nice" + (n)); 
    } 
})(i));