Google Chrome extension: for loop to assign chrome.tabs.create functions
I want to have a list of links, that each open a different Youtube video that has been predefined in links.xml. This file works perfectly, and all the links are generated, but whenever I click on any of them it opens a new开发者_运维百科 tab with the URL of the last link in the list. What am I doing wrong?
<style>
body { width:550px; }
</style>
<script>
var req = new XMLHttpRequest();
req.open("GET", "links.xml");
req.onload = showLinks;
req.send(null);
function showLinks() {
var links = req.responseXML.getElementsByTagName("link");
var p, a, h, t;
for (var i = 0, link; link = links[i]; i++) {
p = document.createElement("p");
a = document.createElement("a");
h = link.getAttribute("http");
t = link.getAttribute("title");
p.appendChild(document.createTextNode((i+1) + ') '));
a.href = h;
a.onclick = function() { chrome.tabs.create( { url: h } ); }
a.appendChild(document.createTextNode(t));
p.appendChild(a);
document.body.appendChild(p);
}
}
</script>
Spacevillain was correct:
it seems that you need to use closures, check this link: http://www.mennovanslooten.nl/blog/post/62
精彩评论