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

编程入门 行业动态 更新时间:2024-10-28 18:28:33
本文介绍了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", "*/*", "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 找到元素

本文发布于:2023-08-06 05:19:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310295.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:弹出窗口   元素   chrome   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!