可以通过以下代码了解JS里的onclick事件:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <style> #divclass { cursor:pointer; } #uiclass { } #uiclass li { display:inline-block; } </style> <script type="text/javascript"> window.onload = function () { document.getElementById("txt").onchange = function () { //alert("我的值改变啦~~~"); //事件的方法里面的this:谁调用的方法,方法里的this就是谁 alert(this.value); }; //通过文本框调用onchange 那么 onchange里面的this就是文本框 // document.getElementById("txt").onchange(); document.getElementById("selNation").onchange = function () { //下拉框的this.value可以获取到选中的option的value值 //var curoptionIndex = this.selectedIndex; //alert(this.childNodes.length);//dom元素的childnodes中包含了所有类型的子节点(html元素节点、文本节点) //alert(this.children.length);//dom元素的children里只包含html元素节点 //alert(this.selectedIndex); //alert(this.value+","+this.innerHTML); var curOptionIndex = this.selectedIndex; var opts = this.children; var selectOpt = opts[curOptionIndex]; alert(selectOpt.innerHTML); }; document.getElementById("txtName").onfocus = focus; document.getElementById("txtName").onblur = blur; document.getElementById("txtPwd").onfocus = focus; var li = document.getElementsByTagName("li"); for (var i = 0; i < li.length; i++) { li[i].onclick = doClick; } }; function doClick() { this.style.backgroundColor = "white"; //选取当前选中li对象的下一个兄弟li对象 var nextObj = this.nextElementSibling; //循环判断是否存在下一个li对象 while (nextObj) { //修改下一个背景颜色 nextObj.style.backgroundColor = "red"; //再把 下一个的下一个对象找出 如果没有了就返回空 nextObj = nextObj.nextElementSibling; } //找出当前选中的li的前一个li,并设置前一个li的背景色 if (isNaN(this.previousElementSibling)) { var preObj = this.previousElementSibling; preObj.style.backgroundColor = "blue"; preObj = preObj.previousElementSibling; } } function focus() { document.getElementById("msgBox").innerHTML = this.value; alert(this.value); } function blur() { alert("我走了~~~"); } //为下拉框 绑定onchange事件 </script> </head> <body> <div id="divBox" style="margin:100px auto;"> <input type="text" value="1" id="txt"/> <select id="selNation"> <option id="1">中国</option> <option id="2">美国</option> <option id="3">韩国</option> </select> <input type="text" id="txtName" value="my i love you~~~~~"/> <input type="text" id="txtPwd" value="me too~~~" /> </div> <div id="msgBox"></div> <div id="divclass"> <ul id="uiclass"> <li>aaaaaaaa</li> <li>bbbbbbbb</li> <li>cccccccc</li> <li>dddddddd</li> </ul> </div> </body> </html>