【问题标题】:How to clear input filed in JS alfter submiting?提交后如何清除JS中的输入字段?
【发布时间】:2023-01-07 18:57:47
【问题描述】:

我试图在使用 textcontent = '' 提交后清除输入字段,但它不起作用。

const inputField = document.querySelector('.input');
document.querySelector('.submit').addEventListener('click', function() {
for (let i = 1; i <= 5; i++) {
    if (document.querySelector(`.position-${i}`).classList.contains('hidden')) {
        document.querySelector(`.position-${i}`).classList.remove('hidden')
        document.querySelector(`.text-${i}`).textContent = inputField.value
        document.querySelector('.input').textContent = ''
        if (!document.querySelector(`.position-${i}`).classList.contains('hidden')) break
    }
}

})

【问题讨论】:

  • .remove className "hidden" 没有意义,然后去检查它是否被删除。
  • 另外,恐怕你做的事情非常错误。好像你把班级当作唯一选择器.通常,在使用类时,您希望将它们全部循环。否则,很明显您可能想要使用 ID——或者……根本没有选择器。 (有时您可以选择 [name="something"] 等属性选择器...)没有看到 HTML 和围绕您的问题的真正问题 - 很难说。
  • 使用.value代替.textContentdocument.querySelector('.input').value = ''。我希望.input是输入标签

标签: javascript


【解决方案1】:

要重置表单,请使用HTMLFormElement.reset()

document.querySelector("#myForm").reset();

除此之外,

HTMLInputElement 没有 .textContent setter。
最终使用.value代替(*阅读下面有关这样做的含义)

// WARNING! Don't use this example to "reset" an input value!
document.querySelector('input').value = '';

  • 这样只会在第一的&lt;input&gt; 在您的应用中找到了。
  • 它会不重置输入值,而是将其覆盖为空字符串。

相反,使用.deaultvalue

要考虑特定表单的所有输入,请使用:

document.querySslectorAll("#myForm input").forEach(elInp => {
  elInp.value = elInp.defaultValue;
});

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多