본문 바로가기
2019/JavaScript

JS onchange

by SOLYI 2019. 12. 9.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        window.onload=function(){
            document.getElementById('sel').onchange=function(){
                //console.log('test') // 옵션 변경할때마다 콘솔에test출력
                
                let d = this.selectedIndex;
         //       console.log(d); //선택하는것에 따라 0,1,2 출력
                
                let d2 = document.getElementsByTagName('option');
                /*console.log(d2[this.selectedIndex]);*/ //아래와 같음.
                console.log(d2[d]);
                
                let b = document.getElementsByTagName('body');
                b[0].style.backgroundColor=d2[d].value;
            }
        }
    </script>
</head>
<body>
   <select name="sel" id="sel">
       <option value="red" selected>빨강</option>
       <option value="blue">파랑</option>
       <option value="yellow">노랑</option>
       <option value="purple">보라</option>
       <option value="gray">회색</option>
       <option value="black">검정</option>
   </select>
    
</body>
</html>

 

반응형

'2019 > JavaScript' 카테고리의 다른 글

JS elementSibling  (0) 2019.12.09
JS addEventListner 이용해서 checkbox 전체선택  (0) 2019.12.09
JS addEventListener 연습  (0) 2019.12.09
JS create Element  (0) 2019.12.09
JS add Event Listener (set Attribute)  (0) 2019.12.09