다음은 JavaScript를 사용하여 부울을 토글하는 코드입니다 -
예시
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-weight: 500; font-size: 18px; color: blueviolet; } </style> </head> <body> <h1>Toggle a boolean using JavaScript</h1> <div class="result"></div> <button class="Btn">Toggle</button> <h3>Click on the above button to toggle the above boolean value</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let boolVal = true; resEle.innerHTML = boolVal; BtnEle.addEventListener("click", () => { boolVal = !boolVal; resEle.innerHTML = boolVal; }); </script> </body> </html>
출력
토글 버튼 클릭 시 -