onclick 이벤트 처리하기
vanilla js 예시입니다. 리액트 X
1. <button>의 onclick 속성에 직접 코드 전달하기
<button onclick="alert('버튼이 클릭되었습니다')">클릭</button>
2. <button>의 onclick 속성에 함수 실행문 전달하기
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">클릭</button>
<script>
function myFunction() {
alert("버튼이 클릭되었습니다.")
}
</script>
</body>
</html>
3. <button>을 DOM으로 조작하기
버튼을 getElementById로 객체로 받아와서 javascript .onclick 메서드로 함수 할당해주기
<!DOCTYPE html>
<html>
<body>
<button id="btnHello">클릭</button>
<script>
document.getElementById("btnHello").onclick = function () {
alert("버튼이 클릭되었습니다.");
};
</script>
</body>
</html>
4. <button>를 javascript 이벤트 리스너로 조작하기
<!DOCTYPE html>
<html>
<body>
<button id="btnHello">클릭</button>
<script>
const myButton = document.getElementById("btnHello");
myButton.addEventListener("click", () => {
alert("버튼이 클릭되었습니다.");
});
</script>
</body>
</html>
쓰고 보니 4가지네요. : P
'인간은 어떻게 배울까' 카테고리의 다른 글
[Python] 파이썬이 함수의 매개변수에 값을 전달하는 방식 (0) | 2023.07.15 |
---|---|
[Mac] 터미널에서 환경변수 잘못 입력해서 기본 명령어도 실행이 안될 때 (0) | 2023.07.13 |
[크롬] 브라우저 주소창에서 검색 안되게 막기 (0) | 2023.07.07 |
[백준-파이썬] 1676번 팩토리얼 0의 개수 (실버5) (0) | 2023.07.03 |
[백준-파이썬] 10870번 피보나치 수 5 (브론즈2) (0) | 2023.07.03 |