2010-12-16 5 views
0

私は、ページ上にいくつかのリンクを動的に追加する拡張機能を持っています。異なるクリックイベントを持つリンクを動的に追加します

問題は、クリックイベントがすべてのリンクに対して同じ変数を送信することです(最後のアイテムのURLはすべてのリンクに対して送信されます)。私はclickイベントが毎回上書きされると信じています。これにはどんな解決策がありますか?

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. 
} 

答えて

1

クロージャは、ループの繰り返しごとに再割り当てされる外部コンテキストの変数を参照しています。

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(url) { 
     return function (evt) {    //click event for this specific link. 
      chrome.extension.sendRequest({'action' : 'showSite','URL' : url}, mysub); 
     } 
    })(url); 

    link_dom.appendChild(text_dom);    //adds text to link. 
    body_dom.appendChild(link_dom);    //adds the link to the website. 
} 
+0

ありがとう、それは完璧に働いています。 – Henrik

関連する問題