动态添加不同点击事件的链接
我有一个扩展,它可以动态地在页面上添加多个链接,并且所有链接都应该触发相同的函数,但具有不同的参数值。
我遇到的问题是,单击事件为所有链接发送相同的变量(为每个链接发送最后一个项目的 url)。我相信点击事件每次都会被覆盖。有什么解决办法吗?
for(var i=1;i < splits.length;i++){ //goes through all xml items.
var link_dom = document.createElement('a'); //creates a link dom.
var url = parseXMLItem(splits[i],"url"); //fetches url from xml item i.
var text_dom = document.createTextNode("test"); //creates a text dom.
link_dom.onclick=function (evt) { //click event for this specific link.
chrome.extension.sendRequest({'action' : 'showSite','URL' : url}, mysub);
}
link_dom.appendChild(text_dom); //adds text to link.
body_dom.appendChild(link_dom); //adds the link to the website.
}
I have an extension which adds several links on a page dynamically, and all the links should trigger the same function but with diffrent parameter values.
The problem I got is that the click event sends the same variable for all my links (the last item's url gets sent for every link). I belive the click event gets overwritten each time. Is there any solution for this?
for(var i=1;i < splits.length;i++){ //goes through all xml items.
var link_dom = document.createElement('a'); //creates a link dom.
var url = parseXMLItem(splits[i],"url"); //fetches url from xml item i.
var text_dom = document.createTextNode("test"); //creates a text dom.
link_dom.onclick=function (evt) { //click event for this specific link.
chrome.extension.sendRequest({'action' : 'showSite','URL' : url}, mysub);
}
link_dom.appendChild(text_dom); //adds text to link.
body_dom.appendChild(link_dom); //adds the link to the website.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
闭包引用外部上下文中的变量,该变量在每次循环迭代时都会重新分配。尝试这样的事情:
The closure is referencing the variable in the outer context, which is reassigned on every loop iteration. Try something like this: