【问题标题】:Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator)) is the error I can't solveUncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator)) 是我无法解决的错误
【发布时间】:2022-11-28 04:11:39
【问题描述】:

错误是:Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

下面是我的整个 js 文件:

const DOMSelectors = {
  button: document.getElementById("btn"),
  form: document.getElementById("form"),
  removeButton: document.getElementById("remove-btn"),
  display: document.getElementById("display-card"),
  formInput: document.querySelectorAll("#form-input"),
  resetButton: document.getElementById("resetbutton"),
  typeInput: document.getElementById("type-input"),
  flavorInput: document.getElementById("flavor-input"),
  brandInput: document.getElementById("brand-input"),
};

DOMSelectors.button.addEventListener("submit", function () {
  let imputs = Array.box;
  typeInput = imputs[1].value;
  flavorInput = imputs[2].value;
  brandInput = imputs[3].value;
  console.log(imputs);
});

function resetbutton() {
  DOMSelectors.brandInput.value = ``;
  DOMSelectors.flavorInput.value = ``;
  DOMSelectors.typeInput.value = ``;
}

function display() {
  h1 = DOMSelectors.typeInput.value;
  h2 = DOMSelectors.flavorInput.value;
  h3 = DOMSelectors.brandInput.value;
  DOMSelectors.display.insertAdjacentHTML(
    "afterbegin",
    `<div class = "display-card"> 
    <h1>${h1}</h1>
    <br>
    <h2>${h2}</h2>
    <br>
    <h3>${h3}</h3>
    <br>
    <button id = "removebtn">Remove</button>
    </div>
       `
  );
}

function destroy() {
  const btn = Array.from(document.getElementById("removebtn"));
  btn.forEach((button) => {
    button.addEventListener("click", function () {
      this.parentElement.remove;
    });
  });
}

DOMSelectors.form.addEventListener("submit", function () {
  event.preventDefault();
  destroy();
  display();
  resetbutton();
});

我在线上收到错误:

  const btn = Array.from(document.getElementById("removebtn"));

我一直无法弄清楚是什么导致了这个错误

我是 JavaScript 的新手,所以我们将不胜感激

【问题讨论】:

  • document.getElementById("removebtn") 显然为 null,这意味着具有该 id 的元素在函数运行时不存在。

标签: javascript


【解决方案1】:

这是说 document.getElementById("removebtn") 正在返回 null。也许您的 DOM 中没有 ID 为“removebtn”的元素?或者也许您在这段代码存在之前运行它?

此外,Array.from 需要一个可迭代的事物列表,但 getElementById 仅返回单个 DOM 元素,因此在这种情况下使用 Array.from 没有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2020-12-14
    • 2021-05-21
    • 2021-10-22
    • 2019-08-13
    • 2022-07-09
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多