VanillaJS 0420
App.js
const loginInput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");
function onLoginBtnClick(){
  const username = loginInput.value;
  if(username === ""){
    alert("please write your name")
  } else if (username.length > 15){
    alert("your name is too long.")
  }
}
loginButton.addEventListener("click",onLoginBtnClick)
index.html
<!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">
  <link rel="stylesheet" href="style.css">
  <title>Momentum</title>
</head>
<body>
  <div id="login-form">
    <input type="text" placeholder="What is your name?"/>
    <button>Log In</button>
  </div>
  <script src="app.js"></script>
</body>
</html>
js 에서 if else문을 이용하는거 보다는 html기능인 required 와 maxlength를 사용해서 같은 기능을 구현할 수 있다.
따라서 위 코드는 아래 코드와 같다.
app.js
const loginInput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");
function onLoginBtnClick(){
  const username = loginInput.value;
  console.log(username)
}
loginButton.addEventListener("click",onLoginBtnClick)
index.html
<!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">
  <link rel="stylesheet" href="style.css">
  <title>Momentum</title>
</head>
<body>
  <div id="login-form">
    <input required
    maxlength="15"
    type="text" 
    placeholder="What is your name?"/>
    <button>Log In</button>
  </div>
  <script src="app.js"></script>
</body>
</html>
js에서 if 문을 삭제하고 html에서 input에 기능을 추가한 것을 볼 수 있다.
js에 너무 많은 기능을 추가하기 보다는 html 자체에 있는 기능을 사용해서 코드를 간략하게 짜도록 노력하자!
Author And Source
이 문제에 관하여(VanillaJS 0420), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hyj3363/VanillaJS-0420저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)