[英]Chrome Extension : Tab issues
當在popup.html中單擊其圖像時,以下代碼嘗試為相應的post對象打開一個新選項卡。 由於某些原因,新標簽為空白,並且無法轉到“帖子”單例中this.Link指定的正確頁面。 任何幫助,將不勝感激!
<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>
您注冊post.displayTab
作為一個事件偵聽器post.imgElement
這意味着價值this
將post.imgElement
當事件監聽器被調用。 因此,沒有Link
屬性( this.Link
是未定義的)。 避免此問題的一種方法是以其他方式注冊事件處理程序:
post.imgElement.addEventListener("click", function() {
post.displayTab();
}, false)
post.displayTab
在這里被稱為post
對象的方法,因此將正確設置this
變量。 另一個選擇是在post.displayTab
停止使用this
post.displayTab
:
this.imgElement = document.createElement("image");
var me = this;
this.displayTab = function(){
chrome.tabs.create({'url' : me.Link}, function(tab){});
}
在me
變量記住了“正確” this
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.