Chrome扩展程序:标签问题

时间:2011-12-03 23:04:55

标签: javascript xml google-chrome google-chrome-extension

下面的代码尝试在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>

1 个答案:

答案 0 :(得分:1)

您在post.displayTab上注册post.imgElement作为事件侦听器,这意味着在调用事件侦听器时this的值将为post.imgElement。因此,没有Link属性(this.Link未定义)。避免此问题的一种方法是以不同方式注册事件处理程序:

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

post.displayTab在此处被称为post对象的方法,因此this变量将被正确设置。另一种选择是停止在this中使用post.displayTab

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

me变量会记住“正确的”this值。