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 找到元素


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01