2011-12-03 95 views
0

下面的代碼嘗試打開相應的發佈對象的新標籤頁,當它的圖像在popup.html中被點擊時。出於某種原因,新選項卡爲空,並且不會按照Post單例中的this.Link所指定的頁面進行。任何幫助,將不勝感激!Chrome瀏覽器擴展程序:標籤問題

<html> 
<head> 
    <style> 
     body { 
      min-width:357px; 
      overflow-x:hidden; 
     } 

     img { 
      margin:5px; 
      border:2px solid black; 
      vertical-align:middle; 
      width:75px; 
      height:75px; 
     } 
    </style> 


    <script> 
     var req = new XMLHttpRequest(); 
     req.open(
     "GET", 
     "http://thekollection.com/feed/", 
     true); 
     req.onload = showPosts; 
     req.send(null); 

     function showPosts() { 
      var elements = req.responseXML.getElementsByTagName("item"); 

      for (var i = 0, item; item = elements[i]; i++) { 
       var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue; 
       var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue; 
       var txtLink = link.toString(); 
       var txtDesc = description.toString(); 

       var start = txtDesc.indexOf("\"") + 1; 
       var end = txtDesc.indexOf(".jpg") + 4; 
       var imgURL = txtDesc.substring(start, end); 

       var post = new function(){ 
        this.Link = txtLink; 
        this.Description = txtDesc; 
        this.ImageURL = imgURL; 
        this.imgElement = document.createElement("image"); 
        this.displayTab = function(){ 
         chrome.tabs.create({'url' : this.Link}, function(tab){}); 
        } 
       } 


       post.imgElement.addEventListener("click", post.displayTab, false) 
       post.imgElement.src = post.ImageURL; 

       document.body.appendChild(post.imgElement); 
      }  
     }  
    </script> 
</head> 
<body> 
</body> 

回答

1

您註冊post.displayTab作爲post.imgElement事件偵聽器,這意味着的this的值將是post.imgElement當事件監聽器被調用。因此,沒有Link屬性(this.Link未定義)。爲了避免這個問題的一個方法是不同的註冊事件處理程序:

post.imgElement.addEventListener("click", function() { 
    post.displayTab(); 
}, false) 

post.displayTab被稱爲這裏這麼this變量將被正確設定post對象的方法。另一種選擇是停止在post.displayTab使用this

this.imgElement = document.createElement("image"); 
var me = this; 
this.displayTab = function(){ 
    chrome.tabs.create({'url' : me.Link}, function(tab){}); 
} 

me變量記住了「正確」 this值。

+0

非常感謝你,這個修好了! – Jasdev

+0

@Jasdev:如果有幫助,請隨時接受答案:http://stackoverflow.com/faq#howtoask –

相關問題