jQuery表单提交事件处理程序没有被调用(chrome扩展)

时间:2014-11-14 16:59:54

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

所以我正在尝试制作一个简单的Chrome扩展程序,在新标签页中打开一个网址。 问题是,我似乎无法弄清楚为什么我提交表单时没有运行我的函数(popup.js中的函数)(通过按Enter键)。

这是我的代码:

的manifest.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();
});

2 个答案:

答案 0 :(得分:1)

这里几个问题:

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

答案 1 :(得分:0)

如果在popup.js中有所有内容,则需要将其包含在$(document).ready(function() {});$(function() {});中。

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