简体   繁体   English

提交后,Chrome扩展程序HTML将焦点设置为输入字段

[英]Chrome Extension HTML Setting Focus to Input Field After Submitting

This is a chrome extension and I am trying to get the focus to return to the text box input after submitting. 这是一个chrome扩展名,我试图让焦点在提交后返回到文本框输入。

Basically, I want the input process to be as follows: 1. User types input in 2. User presses enter or clicks the button 3. Form submits, doesn't refresh, resets itself, and retains focus so the user can easily add more inputs. 基本上,我希望输入过程如下:1.用户键入2.在用户中输入或单击按钮3.表单提交,不刷新,自行重置并保持焦点,以便用户可以轻松添加更多内容输入。

If the user presses enter, the focus is retained. 如果用户按Enter,则焦点将保留。 However, as soon as the user presses the button (add website), the text box input loses focus. 但是,一旦用户按下按钮(添加网站),文本框输入就会失去焦点。 I'm not sure why the following HTML and corresponding JavaScript don't work: 我不确定以下HTML和相应的JavaScript为什么不起作用:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="popup.js"></script>
    <title>Add a website to block</title>
  </head>
  <body>
    <form id="addWebsiteForm">
    Website Address: <input type="text" id="websiteAddress"><br>
    <input type="submit" value="Add Website">
    </form>
  </body>
</html>

JavaScript: JavaScript:

var addWebsiteForm; var addWebsiteForm;

document.addEventListener('DOMContentLoaded', function(){
  addWebsiteForm = document.getElementById("addWebsiteForm");
  addWebsiteForm.addEventListener('submit', addWebsite);
});

function addWebsite(event) {
  addWebsiteForm.focus();
  event.preventDefault();
  var websiteAddress = document.getElementById("websiteAddress").value;
  var storedWebsites;

  chrome.storage.local.get('websites', function(objects) {

    if (!objects.websites) {
        storedWebsites = [];
    } else {
        storedWebsites = objects.websites;
    }

    storedWebsites.push(websiteAddress);
    chrome.storage.local.set({'websites':storedWebsites});
    addWebsiteForm.reset();
  });
}

You've actually only made one small error. 您实际上只犯了一个小错误。 You're focusing on the whole form instead of the input field. 您将重点放在整个表单而不是输入字段上。 In the top of your JavaScript create another line with the input text's id. 在JavaScript的顶部,用输入文本的ID创建另一行。 Then set focus to that one after resetting the form. 重置表单后,将焦点设置为该焦点。

Like this, 像这样,

websiteAddress = document.getElementById("websiteAddress");

websiteAddress.focus();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM