当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript下给元素添加事件的方法与代码

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript下给元素添加事件的方法与代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 92 ::
收藏到网摘: n/a

最简单的是这样:
<input type="button" onclick="alert(this.value)" value="我是 button" />
动态添加onclick事件:
<input type="button" value="我是 button" id="bu">
<script type="text/javascript">
var bObj=document.getElementById("bu");
bObj.onclick= objclick;
function objclick(){alert(this.value)};
</script>
如果使用匿名函数 function(){},则如下面所示:
<input type="button" value="我是 button" id="bu">
<script type="text/javascript">
var bObj=document.getElementById("bu");
bObj.onclick=function(){alert(this.value)};
</script>
上面的方法其实原理都一样,都是定义 onclick 属性的值。值得注意的是,如果多次定义 obj.onclick,例如:obj.onclick=method1; obj.onclick=method2; obj.onclick=method3,那么只有最后一次的定义obj.onclick=method3才生效,前两次的定义都给最后一次的覆盖掉了。
再看 IE 中的 attachEvent:
<input type="button" value="我是拉登" id="bu">
<script type="text/javascript">
var bObj = document.getElementById("bu");
bObj.attachEvent("onclick",method1);
bObj.attachEvent("onclick",method2);
bObj.attachEvent("onclick",method3);
function method1(){alert("第一个alert")}
function method2(){alert("第二个alert")}
function method3(){alert("第三个alert")}
</script>
执行顺序是 method3 > method2 > method1 ,先进后出,与堆栈中的变量相似。需要注意的是attachEvent 中第一个参数是on开头的,可以是 onclick/onmouseover/onfocus 等等
据说(未经确认验证)在 IE 中使用 attachEvent 后最好再使用 detachEvent 来释放内存
再看看 Firefox 中的的 addEventListener:
<input type="button" value="我是布什" id="bu">
<script type="text/javascript">
var bObj = document.getElementById("bu");
bObj.addEventListener("click",method1,false);
bObj.addEventListener("click",method2,false);
bObj.addEventListener("click",method3,false);
function method1(){alert("第一个alert")}
function method2(){alert("第二个alert")}
function method3(){alert("第三个alert")}
</script>
可以看到,在 ff 中的执行顺序是 method1 > method2 > method3 , 刚好与 IE 相反,先进先出。需要注意的是 addEventListener 有三个参数,第一个是不带“on”的事件名称,如 click/mouseover/focus等。