Chrome扩展弹出窗口无法通过ID查找元素 [英] chrome extension popup cannot find element by ID
问题描述
我知道类似的问题已经被多次提出,但我还没有找到解决方案。我的问题很简单。我想要做的就是测试popup.html上的操作,在这里,我弹出一个单击按钮,当我点击它时,我想显示警报。但没有发生。它没有找到元素。我不明白这里发生了什么问题。
manefest.json
{
name:test,
version:1.0,
description:test,
manifest_version:2,
browser_action:{
default_icon:logo.png,
default_popup:popup.html
},
权限:[
标签,
http:// * / *,
通知
]
}
popup.html
< ; HTML>
< head>
< title>测试< /标题>
< script type =text / javascriptsrc =jquery.js>< / script>
< script type =text / javascriptsrc =popup.js>< / script>
< / head>
< body>
< button id ='btn'>点击< / button>
< / body>
< / html>
popup.js
$ b $点击(函数(){
alert(test);
};
$('#btn' code>
解决方案问题是您的代码尽快执行< ;脚本>
标记被读取,即在DOM中存在元素之前。 $ b
将它包装在 $(document) .ready()
,你很好去:
$(document).ready(函数(){
/ *您的代码* /
});
对于非jQuery解决方案,将其包装在 DOMContentLoaded
侦听器中:
document.addEventListener(DOMContentLoaded,function(){
/ *您的代码* /
});
最后,您可以简单地将< script>
标记移动到< body>
,但这是一个不太稳健的解决方案。
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.
manefest.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");
};
解决方案 The problem is that your code executes as soon as <script>
tag is read, i.e. before your element exists in DOM.
Wrap it in $(document).ready()
and you're good to go:
$(document).ready(function() {
/* your code */
});
For a non-jQuery solution, wrap it in DOMContentLoaded
listener:
document.addEventListener("DOMContentLoaded", function() {
/* your code */
});
Finally, you can simply move the <script>
tag to the end of <body>
, but it's a less robust solution.
这篇关于Chrome扩展弹出窗口无法通过ID查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!