trim去除空格的用法

84 阅读1分钟

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    用户名:<input type="text" placeholder="请输入用户名" /> <br />
    <br />

    密码: <input type="password" placeholder="请输入密码" />
    <button>登录</button>
  </body>
  <script>
    const input1 = document.querySelector("input:nth-of-type(1)");
    const input2 = document.querySelector("input:nth-of-type(2)");
    const button = document.querySelector("button");
    // 如果用戶名输入框里面输入的是空格,就不能登录
    // 否则就弹出登录成功
    button.onclick = function () {
      // !input1.value.trim()表示去除空格以后啥也没有
      if (!input1.value.trim()) {
        alert("不能登录");
      }
    };
  </script>
</html>
****