JS基础学习四:绑定事件
添加事件
IE: attachEvent
Other: addEventListener
var button = document.getElementById("buttonId");if(button.addEventListener){ button.addEventListener("click",eventFunction,false);}else if(button.attachEvent){ button.attachEvent("onclick",eventFunction);}function bindEvent() {var button = document.getElementById("buttonId");if (button.addEventListener) {alert("Other browser");//button.addEventListener("click",showEvent,false);//button.addEventListener("click",showEvent2,false);button.addEventListener("click", showEvent, true);button.addEventListener("click", showEvent2, true);} else if (button.attachEvent) {alert("IE browser");button.attachEvent("onclick", showEvent);button.attachEvent("onclick", showEvent2);}}function removeEvent() {var button = document.getElementById("buttonId");if (button.removeEventListener) {alert("Other browser");//button.removeEventListener("click",showEvent,false);button.removeEventListener("click", showEvent, true);} else if (button.detachEvent) {alert("IE browser");button.detachEvent("onclick", showEvent);}}function showEvent(e) {if (window.event != undefined) {window.event.cancelBubble = true;} else if (e.stopPropagation) {e.stopPropagation();}alert("Event here!");}function showEvent2() {alert("Other event here!");}function divEvent() {alert("Div Event");}<div onclick="divEvent()"> <input type="button" id="buttonId" value="showEvent"/></div>
window.onload=function(){ //绑定键盘事件 document.onkeydown=showkey;}function showkey(e){ var key; if(window.event) key= window.event.keyCode; else key= e.keyCode; alert(String.fromCharCode(key));}document.onmouseover= showPosition;