1. 程式人生 > >JS點擊事件

JS點擊事件

tle utf add this cli doctype pre tag html

 1 <!DOCTYPE html>
 2 <html lang="cn">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <style>
 7         span{
 8             padding: 5px 10px;
 9             background-color:darkgreen;
10             /* width: 20px; */
11             /*
height: 20px; */ 12 /* display: block; */ 13 } 14 </style> 15 <script type="text/javascript"> 16 window.onload = function() { 17 var hlist = document.getElementsByTagName(span); 18 //console.log(hlist.length) 19 hlist[
0].style.backgroundColor = "brown"; 20 for (var i = 0; i < hlist.length; i++) { 21 var htag = hlist[i]; 22 htag.onclick = function() { 23 //alert(this.innerHTML); 24 setColor(hlist,this.innerHTML - 1); 25 }
26 } 27 } 28 setColor = function(hlist,index){ 29 for(var i = 0; i < hlist.length; i++){ 30 if(index != i){ 31 //hlist[i].setAttribute("class", "a"); 32 hlist[i].style.backgroundColor = "darkgreen"; 33 }else{ 34 //hlist[i].setAttribute("class", "b"); 35 hlist[i].style.backgroundColor = "brown"; 36 } 37 } 38 } 39 </script> 40 </head> 41 <body> 42 <span>1</span> 43 <span>2</span> 44 <span>3</span> 45 <span>4</span> 46 <span>5</span> 47 <span>6</span> 48 <span>7</span> 49 <span>8</span> 50 <span>9</span> 51 </body> 52 </html>

JS點擊事件