javascript 检查用户输入是否为空

qvk1mo1f  于 2023-02-21  发布在  Java
关注(0)|答案(3)|浏览(179)

我在检查输入字段是否为空时遇到了一些麻烦,当它为空时,我想将其恢复为h1标记中的内容。

<body>
    <h1>Enter Your Username</h1>
    <input type="text" id="username" />
  </body>

const input = document.querySelector("input");
const h1 = document.querySelector("h1");

input.addEventListener("input", (e) => {
  h1.innerText = `Welcome ${input.value}`;
});

if (input.length === 0) {
  h1.innerText = "Enter Your Username";
}
nukf8bse

nukf8bse1#

输入没有长度属性。您的意思可能是:

if (input.value.length === 0) {
  h1.innerText = "Enter Your Username";
}

或不带空格:(感谢Roko)

if (input.value.trim().length === 0) {
      h1.innerText = "Enter Your Username";
    }
wn9m85ua

wn9m85ua2#

当前输入长度检查不在事件处理程序内部。理想情况下,您希望在每次输入值更改时检查输入是否为空。因此,您希望它位于input.addEventListener回调中

input.addEventListener("input", function(e) {
  h1.innerText = this.value.length === 0 ?
    "Enter Your Username" :
    `Welcome ${input.value}`; 
});
lo8azlld

lo8azlld3#

**HTML**
<body>
    <h1>Enter Your Username</h1> 
    <input type="text" id="username">
</body>

**JS** 
let inputEl = document.querySelector('input') 

let h1 = document.querySelector('h1') 
inputEl.addEventListener('input',()=>{ 
  h1.innerText = "Welcome, " + inputEl.value 
 if (inputEl.value.length === 0) h1.innerText = "Enter Your Username";
})

相关问题