본문 바로가기

개발하자/자바스크립트

이벤트처리 2가지 문법(버튼 색상 바꾸기 예제)

[sy]
<script>
function 함수명(){
이벤트처리부분
}
</script>

<태그명 on이벤트명="함수명()">

[ex] 버튼을 누르면 버튼배경색상이
빨간색이 될 수 있도록 소스코드를 작성하시오.
단, 위 문법을 참고한다.

<html>
 <head>
 <script>
function a(o){
o.style.background=o.value;
}
 </script>
 </head>
 <body>
 <input type="button" value="red"  onclick=a(this)>
 </body>
</html>


[sy]
<script>
window.onload=function(){
객체명.on이벤트명=function(){
이벤트처리부분
}
}
</script>

<태그명 id="객체명">

[ex] 버튼을 누르면 버튼배경색상이
빨간색이 될 수 있도록 소스코드를 작성하시오.
단, 위 문법을 참고한다.

<html>
 <head>
 <script>
 window.onload=function(){
aa.onclick=function(){
 this.style.backgroundColor=this.value;
}
 }
 </script>
 </head>
 <body>
 <input type="button" value="red" id=aa>
 </body>
</html>