<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>事件监听 </title> <script type="text/javascript"> function run(){ alert("你好");} /* onfocus 元素获取焦点 onblur 元素失去焦点 */ function run1() { alert("获取焦点"); } function run2() { alert("失去焦点"); } /* onload 页面载入完毕时运行。。。 能够有效避免 使用元素标签时/获取元素对象时 元素未载入 */ function run3() { alert(document.getElementById("HH").innerHTML); } /* onchange() 当值改变时调用 */ function run4() { alert("选择的值改变了"); } /* javascript 事件绑定方式 1、HTML属性绑定方式 2、HTML DOM 方法绑定 */ function run5() { var arr = document.getElementsByTagName("input"); alert(arr.length); alert(arr[0].value); } function run6(x) { alert(x.value); } /* 假设输入数字 放行 假设输入非数字 阻止默认事件(键盘输入键码值事件) 0~9 键码值 48~57 8相应退格键 */ function run7() { //获取事件对象 var e = window.event; //获取键码值进行推断 var code = e.keyCode; if(!(code)>=48 && code<=57) { // 不是数字 阻止默认事件 e.returnValue = false; } } function run8(e) { //获取键码值 var code; if(e&&e.preventDefault) { //火狐或者其它浏览器 code=e.which; } else { //IE code=window.event.keyCode; } //通过键码值进行推断 !(48~57) 非数字 而且 不是退格键 8 if(!((code>=48 && code<=57)||(code==8))) { //阻止默认事件 if(e&&e.preventDefault) { //火狐或者其它浏览器 e.preventDefault(); }else { //IE window.event.returnValue=false; } } } </script> </head> <body onload="run3()"> <input type="button" value="我是按钮 " onclick="run()" /> <input type="text" onfocus="run1()" onblur="run2()" /> <span id="HH">body启动</span> <select onchange="run4()"> <option value="bj">北京</option> <option value="sh">上海</option> <option value="sz">深圳</option> </select> <p></p> <input type="button" value="按钮1" onclick="run5()" /> <input type="button" value="按钮2" onclick="run6(this)" /> <!-- ------------------------------------------------- --> <input type="text" id="i1" onkeydown="run7()" /><br/> <input type="text" id="i2" onkeydown="run8(event)" /><br/> </body> </html>