单击链接上的处理程序无效

时间:2013-03-17 07:16:26

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

我有一个chrome扩展程序,我有

popup.html我调用jquery.js,popup.js和link.js

    ...
    <script src="jquery.js"></script>
    <script src="popup.js"></script>
    <script src="link.js"></script>
  </head>

popup.js

var streamGenerator = {

  /* Twitch URL to the top 20 streams */
  searchOnTwitch_: 'https://api.twitch.tv/kraken/streams?limit=20',

  /* XHR Request to grab those streams */
  requestStreams: function() {
    var req = new XMLHttpRequest();
    req.open("GET", this.searchOnTwitch_, true);
    req.onload = this.showStreams_;
    req.send(null);
  },

  /* onload event inserting the streams into the DOM */
  showStreams_: function(e) {
    var streams = JSON.parse(e.target.responseText).streams;

    for (var i=0; i < streams.length; i++) {
      var stream = {
        game: streams[i].game,
        name: streams[i].channel.name,
        viewers: streams[i].viewers,
        link: streams[i].channel.url,
      };

      $('tbody').append('<tr>'
        + '<td>' + stream.game + '</td>'
        + '<td>' + '<a href=' + stream.link + '>' + stream.name + '</a></td>'
        + '<td>' + stream.viewers + '</td></a>'
      );
    }
  }
};

document.addEventListener('DOMContentLoaded', function() {
  streamGenerator.requestStreams();
});

然后是link.js

$(function() {
  $('a').click(function(){
    chrome.tabs.create({url: $(this).attr('href')});
  });
})

弹出窗口可以显示它应该显示的内容,但链接不会打开新选项卡。

如果我转到chrome的控制台,我没有收到任何错误,但是如果我复制/粘贴link.js jquery,则链接会起作用;

我做错了什么?!

1 个答案:

答案 0 :(得分:1)

您的代码在 popup.js之前加载link.js 。相关部分按以下顺序执行:

// popup.js
$(function() {
    $('a').click( ... );
})
// link.js
document.addEventListener('DOMContentLoaded', function() {
    streamGenerator.requestStreams(); //<-- Creates the links
});

$(func)大致等于document.addEventListener('DOMContentLoaded', func),所以你所做的实际上是这样的:

// Run after the DOMContentLoaded "domready" event:
$('a').click(...);
streamGenerator.requestStreams(); // Creates the links

首先,您将click事件绑定到所有现有锚点(无)。此后您将添加新链接。这个序列显然不起作用。

可以通过交换popup.jslink.js的顺序,或使用event delegation来解决:

$(document).on('click', 'a', function() {
    chrome.tabs.create({url: this.href});
});