Jquery在chrome扩展选项页面中验证

时间:2016-09-29 11:44:33

标签: javascript html google-chrome-extension

全新的这个以及JavaScript和编码一般,所以我的道歉在我开始之前就出去了。

我一直在尝试使用jquery.validate.min.js来检查我一直试图创建的Chrome扩展程序选项页面的文字输入。

当我将<form>标记添加到options.html页面时,事情就会横向移动:只要您点击“保存”按钮,所有options_ui.chrome_style格式都会丢失。

我已使用chrome扩展程序options example并获得相同的结果。

mainfest.json

{
 "manifest_version": 2,
 "name": "Options Test extension",
 "version": "1.0",

 "options_ui": {
  "page": "options.html",
  "chrome_style": true
 }
}

options.html

<!DOCTYPE html>
<html>
 <head>
  <title>My Test Extension Options</title>
  <style>
   body: { padding: 10px; }
  </style>
 </head>

<body>
 <form id="form_a">
   Favorite color:
    <select id="color">
    <option value="red">red</option>
       <option value="green">green</option>
       <option value="blue">blue</option>
       <option value="yellow">yellow</option>
    </select>

    <label>
      <input type="checkbox" id="like">
        I like colors.
    </label>

    <div id="status"></div>
      <button id="save">Save</button>
   </form>
   <script src="options.js"></script>
  </body>
 </html>

options.js

 // Saves options to chrome.storage.sync.
 function save_options() {
  var color = document.getElementById('color').value;
  var likesColor = document.getElementById('like').checked;
  chrome.storage.sync.set({
   favoriteColor: color,
   likesColor: likesColor
 }, function() {
  // Update status to let user know options were saved.
  var status = document.getElementById('status');
  status.textContent = 'Options saved.';
  setTimeout(function() {
    status.textContent = '';
  }, 750);
 });
 }

 // Restores select box and checkbox state using the preferences
 // stored in chrome.storage.
 function restore_options() {
   // Use default value color = 'red' and likesColor = true.
   chrome.storage.sync.get({
     favoriteColor: 'red',
     likesColor: true
   }, function(items) {
     document.getElementById('color').value = items.favoriteColor;
     document.getElementById('like').checked = items.likesColor;
   });
 }
 document.addEventListener('DOMContentLoaded', restore_options);
 document.getElementById('save').addEventListener('click',
     save_options);

当我无法使用<form>时,如果我在自己的扩展程序中输入了文本输入,我将如何验证输入?

1 个答案:

答案 0 :(得分:1)

“事情侧身”的含义可能是<button> elements的默认行为。

如果此类元素位于<form>元素内,则默认情况下的行为类似于提交按钮。这不是你想要的:它重新加载页面(显然有一个额外的效果是不应用chrome_style,因为它没有明确加载“作为选项页面”)。

通过指定按钮类型可以解决您的问题:

<button type="button" id="save">Save</button>

或者,您可以在preventDefault()中的事件对象上调用save_options(如果您添加了事件参数)。但指定按钮类型更清晰。