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

标签 javascript jquery html google-chrome google-chrome-extension

所以我试图制作一个简单的 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/

相关文章:

jquery - 滚动到 anchor 后关闭导航栏

php - 当 MySQL 记录更改时,如何更新页面上显示的值?

html - html 表格单元格中的新行 (\n)

javascript - Aptana Studio 3 MAC 操作系统在滚动 JavaScript 文件时间歇性卡住

javascript - axios中如何处理异步任务

javascript - 如何使用knockout.js组件正确创建分页?

javascript - PHP Ajax 不创建 post 变量

html - Angular 5 星评级栏

javascript - $scope 和此技术在通过服务共享数据方面有何不同?

javascript - jquery - 获取2个数组的相似值的索引