chrome 扩展弹出窗口无法按 ID 找到元素

我知道类似的问题已经被问过很多次,但我还没有找到适合我的解决方案.我的问题很简单.我要做的就是测试 popup.html 上的操作,因为在这里,我在弹出窗口上有一个单击按钮,当我单击它时,我想显示警报.但是什么也没发生.它没有找到元素.我不明白这里出了什么问题.

I know similar questions have been asked many times, but I didn't find a solution for mine yet. My question is really simple. All I want to do is to test actions on popup.html, for here, I have a click button on popup, when I click it, I want to show alert. But nothing happened. It's not finding the element. I don't understand what's going wrong here.

ma​​nefest.json

{
  "name": "test",
  "version": "1.0",
  "description": "test",
  "manifest_version":2,
  "browser_action": {
    "default_icon": "logo.png",
    "default_popup":"popup.html"
  },
  "permissions": [
    "tabs", 
    "http://*/*",
    "notifications"
  ]
}

popup.html

<html>
  <head>
    <title>Test</title>
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
    <button id='btn'>click</button>
  </body>
</html>

popup.js

$('#btn').click(function (){
   alert("test");
};

推荐答案

问题是你的代码在 <script> 标签被读取后立即执行,即在你的元素存在于 DOM 之前.

The problem is that your code executes as soon as <script> tag is read, i.e. before your element exists in DOM.

将它包装在 $(document).ready() 中就可以了:

Wrap it in $(document).ready() and you're good to go:

$(document).ready(function() {
  /* your code */
});

对于非 jQuery 解决方案,将其包装在 DOMContentLoaded 监听器中:

For a non-jQuery solution, wrap it in DOMContentLoaded listener:

document.addEventListener("DOMContentLoaded", function() {
  /* your code */
});

最后,您可以简单地将 <script> 标记移动到 <body> 的末尾,但这是一个不太可靠的解决方案.

Finally, you can simply move the <script> tag to the end of <body>, but it's a less robust solution.

相关文章