chrome extension popup cannot find element by ID(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.
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");
};
推荐答案
问题是你的代码在 <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.
这篇关于chrome 扩展弹出窗口无法按 ID 找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:chrome 扩展弹出窗口无法按 ID 找到元素
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
