본문 바로가기

개발하자/자바스크립트

버튼이벤트 처리 3가지 방법

1) 태그에 onclick

<html>
<head>
<script>
window.onload=function(){

}

function a(buttonObj){
buttonObj.style.backgroundColor=buttonObj.value;
}
</script>
</head>
<body>
<input type="button" value="red" id="b1" onclick="a(this)"><br>
<input type="button" value="blue" id="b2" onclick="a(this)"><br>
<input type="button" value="gray" id="b3" onclick="a(this)"><br>

</body>
</html>

2)선언과 동시에 호출

<html>
<head>
<script>
window.onload=function(){
b1.onclick=function(){ b1.style.backgroundColor=b1.value; }
b2.onclick=function(){ b2.style.backgroundColor=b2.value; }
b3.onclick=function(){ b3.style.backgroundColor=b3.value; }
}
</script>
</head>
<body>
<input type="button" value="red" id="b1"><br>
<input type="button" value="blue" id="b2"><br>
<input type="button" value="gray" id="b3"><br>
</body>
</html>

 

3)함수 선언

<html>
<head>
<script>
window.onload=function(){
b1.onclick=clickFunc;
b2.onclick=clickFunc;
b3.onclick=clickFunc;
}
function clickFunc(){
this.style.backgroundColor=this.value;
}
</script>
</head>
<body>
<input type="button" value="red" id="b1"><br>
<input type="button" value="blue" id="b2"><br>
<input type="button" value="gray" id="b3"><br>
</body>
</html>

'개발하자 > 자바스크립트' 카테고리의 다른 글

내용 복사/지우기 함수이용  (0) 2015.02.14
이벤트처리 2가지 문법(버튼 색상 바꾸기 예제)  (0) 2015.02.14
함수호출  (0) 2015.02.14
eval() 로 함수호출  (0) 2015.02.14
eval()  (0) 2015.02.14