WEB项目中,我们常常会碰到要动态对相应的对象添加事件,如下,有id="txtPrice"的文本框控件:
<div><input type="text" id="txtPrice" name = "txtPrice" value = "0"/> <div>
现在我们为其动态添加一事件,JS核心代码如下:
document.getElementById("txtPrice").attachEvent("onblur", function (){alert("添加事件成功!")});
【补充】
有时候为了实现不同浏览器之前的兼容,我们会这样写:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->1 if(window.attachEvent){document.getElementById("txtPrice").attachEvent("onblur", function (){alert("添加事件成功!")});}else{document.getElementById("txtPrice").addEventListener("onblur", function (){alert("添加事件成功!")},false);}
以上这篇JS动态给对象添加事件的简单方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。