gpt4 book ai didi

javascript - jQuery 表单提交事件处理程序不会被调用(chrome 扩展)

转载 作者:行者123 更新时间:2023-12-03 11:25:24 25 4
gpt4 key购买 nike

所以我试图制作一个简单的 chrome 扩展,它在新选项卡中打开一个 url。问题是,我似乎无法弄清楚为什么当我提交表单(按 Enter 键)时我的函数(popup.js 中的函数)没有运行。

这是我的代码:

ma​​nifest.json

{
"manifest_version": 2,

"name": "Chromerator",
"description": "Vim-like functionality added to chrome",
"version": "1.0",

"permissions": [
"tabs"
],

"background": {
"scripts": ["jquery-2.1.1.min.js"]
},

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}

popup.html

<!doctype html>
<html>
<head>
<style type="text/css">
body {
min-width: 300px;
max-width: 300px;
}

#q {
width: 100%;
}
</style>
</head>
<script src="popup.js"></script>
<form class="f">
<input type="text" id="q" autofocus></input>
</form>
</body>
</html>

popup.js

$('.f').submit(function ( event ) {
var url = "http://" + &('#q').val();
chrome.tabs.create({ 'url': url });
event.preventDefault();
});

最佳答案

这里有几个问题:

1) 您的代码中有一个拼写错误。

&('#q').val();

应该是

$('#q').val();

2) 正如@Magnus Engdal 提到的,你需要在 dom 准备好后包装你的事件处理程序:

$(function() {
$('.f').submit(function ( event ) {
var url = "http://" + $('#q').val();
chrome.tabs.create({ 'url': url });
event.preventDefault();
});
});

3) 内容脚本不在扩展的上下文中运行。您需要在 popup.html 中包含 jquery

<!doctype html>
<html>
<head>
<style type="text/css">
body {
min-width: 300px;
max-width: 300px;
}

#q {
width: 100%;
}
</style>
</head>
<script src="jquery-2.1.1.min.js"></script>
<script src="popup.js"></script>
<form class="f">
<input type="text" id="q" autofocus></input>
</form>
</body>
</html>

gl。

关于javascript - jQuery 表单提交事件处理程序不会被调用(chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26935147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com