想知道如何根据输入向 html 页面添加标签或文本?

Wondering how to add label or text to html page based on input?

我正在制作 chrome 扩展程序,我想知道如何根据按钮触发的输入框添加标签。

我尝试了很多方法,例如更改我使用的标签的 innerHTML .value 但没有任何效果。这是代码:

popup.js:

let AddNote = document.getElementById("AddNote");
let input = document.getElementById("input");

function addnote() {
    var elem = document.createElement('label');
    elem.innerHTML = input.value;    
    document.getElementsByTagName('body')[0].appendChild(elem);
}

chrome.storage.sync.get("note", ({ note }) => {
    AddNote.addEventListener("click", addnote);
  });

popup.html:

<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <form>
      <button id="AddNote">+</button>
      <input type="text" id="input"></input>
      <label id="label"></label>
    </form>
  </body>
</html>

background.js:

let note = '';

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ note });
  console.log('Set note variable to empty.', `note: ${note}`);
});

manifest.json:

{
    "name": "name",
    "description": "desc.",
    "version": "1.0",
    "manifest_version": 3,
    "service_worker": "background.js",
    "action": {
        "default_popup": "popup.html"
      }
  }

let AddNote = document.getElementById("addNotes");

AddNote.addEventListener("click", function () {
      let elem = document.createElement('label')
      let space = document.createElement('br')
      elem.innerHTML = input.value;
      document.getElementsByTagName('body')[0].appendChild(space);
      document.getElementsByTagName('body')[0].appendChild(elem);

});

/* chrome.storage.sync.get("note", ({ note }) => {
   AddNote.addEventListener("click", addnote);
   });
*/
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
      <button id="addNotes">+</button>
      <input type="text" id="input">
      <label id="label"></label>
  </body>
</html>

什么我added/changed

1. 输入标签为空,表示不需要结束标签。所以我从你的 HTML 中删除了它正在关闭。

2. 我对 `chrome.storage.sync.get()` 进行了评论,因为这仅在堆栈片段是扩展时才有效,而事实并非如此。
3. 在`br`标签的帮助下,每次添加标签之前我都添加一个br,这样所有的标签就不会出现在同一行。如果不需要,可以将其删除。

主要问题

在 HTML5 中,如果您有一个没有 `action` 属性的表单标签,那么数据将被发送到它自己的页面。话虽这么说,当单击“+”按钮时,页面会重定向到自身(看起来像刷新),导致错误的结论认为您的代码不起作用。我从你的 HTML 中删除了 `form` 标签。