<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> li { list-style:none; 114px; height:140px; background:url(img/normal.png); float:left; margin-right:20px; } </style> <script> window.onload = function (){ var aLi = document.getElementsByTagName('li'); // var onOff = true; // 只能控制一组! for( var i=0; i<aLi.length; i++ ){ aLi[i].onOff = true; aLi[i].onclick = function (){ // alert( this.style.background ); // 背景不能判断 // color red #f00 // 相对路径 if ( this.onOff ) { this.style.background = 'url(img/active.png)'; this.onOff = false; } else { this.style.background = 'url(img/normal.png)'; this.onOff = true; } }; } }; </script> </head> <body> <ul> <li></li> <li></li> <li></li> </ul> </body> </html>
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script> window.onload = function (){ var aBtn = document.getElementsByTagName('input'); // 想建立“匹配”“对应”关系,就用索引值 var arr = [ '莫涛', '张森', '杜鹏' ]; for( var i=0; i<aBtn.length; i++ ){ aBtn[i].index = i; // 每个都加一个属性,自定义属性(索引值) aBtn[i].onclick = function (){ // alert( arr[ this.index ] ); this.value = arr[ this.index ]; }; } }; </script> </head> <body> <input type="button" value="btn1" /> <input type="button" value="btn2" /> <input type="button" value="btn3" /> </body> </html>
window.onload = function (){ var aBtn = document.getElementsByTagName('input'); // aBtn[0].abc = 123; // 自定义属性 // alert( aBtn[0].abc ); // aBtn[0].abc = 456; // JS 可以为任何HTML元素添加任意个 自定义属性 for( var i=0; i<aBtn.length; i++ ){ aBtn[i].abc = 123; aBtn[i].xyz = true; } }; arrLi[i].onclick = function (){ for( var i=0; i<arrLi.length; i++ ){ if( arrLi[i] !=this ){ arrLi[i].className = ''; } } if( this.className == '' ){ this.className = 'hover'; }else{ this.className = ''; } }; for( var i=0; i<aUl.length; i++ ){ aLi = aUl[i].getElementsByTagName('li'); for( var j=0; j<aLi.length; j++ ){ arrLi.push( aLi[j] ); } } for( var i=0; i<aH2.length; i++ ){ aH2[i].index = i; aH2[i].onclick = function (){ for( var i=0; i<aH2.length; i++ ){ if( i != this.index ){ aUl[i].style.display = 'none'; aH2[i].className = ''; } } if( this.className == '' ){ aUl[this.index].style.display = 'block'; this.className = 'active'; } else { aUl[this.index].style.display = 'none'; this.className = ''; } }; }