簡體   English   中英

Chrome擴展程序:選項卡問題

[英]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這意味着價值thispost.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM