JavaScript事件处理程序

JavaScript中的事件处理程序主要分为3种:

  • HTML事件处理程序:

    <script type="text/javascript">
// HTML事件处理程序
function showMessage(){
alert("clicked!");
};
</script> <button id="btn" onclick="showMessage()">click me!</button>
  • DOM0级事件处理程序:  

<button id="btn">click me!</button>

    <script type="text/javascript">
var btn = document.getElementById("btn"); // DOM0 级事件处理程序
btn.onclick = function(){
alert("clicked!");
};
</script>
  • DOM2级事件处理程序:

<button id="btn">click me!</button>

    <script type="text/javascript">
var btn = document.getElementById("btn"); // DOM2级事件处理程序, 第三个参数:false表示在冒泡阶段调用事件处理程序
btn.addEventListener("click", function(){
alert("clicked!");
}, false);
</script>

附上兼容性事件绑定函数:

function listenEvent(eventTarget, eventType, eventHandler){
if(eventTarget.addEventListener){
eventTarget.addEventListener(eventType, eventHandler, false);
}
else if(eventTarget.attachEvent){
eventType = 'on' + eventType;
eventTarget.attachEvent(eventType, eventHandler);
}
else{
eventTarget['on' + eventType] = eventHandler;
}
}
上一篇:-Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.


下一篇:MySQL主从复制、半同步复制和主主复制概述