如何在Javascript中加入多个事件处理程序,如下所示:
onClick="doSomething();" onKeyUp="doSomething();" onLoad="doSomething();"
答案 0 :(得分:6)
function doSomething(){ console.log("Done!"); }
var element = document.getElementById("my-element");
element.onClick = element.onKeyUp = element.onLoad = doSomething;
答案 1 :(得分:0)
我建议使用javascript库的代码添加事件来抽象远离你自己的浏览器差异。
我还建议将事件本身传递给函数(原型和jquery都这样做)。
<script>
function doSomething(event){
/*your code here*/
/*this refers to the dom node in both libraries*/
};
</script>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script>
$("my-element").bind("click keyup load", doSomething);
</script>
<script src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
<script>
$('my-element').observe('click', doSomething);
$('my-element').observe('keyup ', doSomething);
$('my-element').observe('load', doSomething);
</script>