DOM绑定事件的三种方式
参考事件绑定原理
- 在DOM中绑定。
在DOM中绑定有两种方式:
- 直接在html中onXxxx = “jsCode”
- 在html中onXxx = “handleName()”,然后在js文件中定义
function handleName() {jsCode}
<button οnclick="alert('111')" type='button'></button>
<button οnclick="myClick()"></button>
在js中绑定。
elementObj.onXxx = function(){}
elementObj.οnclick=function() {
alert('111')
}
- 利用事件监听,但是事件监听要考虑到浏览器兼容性
Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
elementObj.addEleventListener(type, handele, useCapture) // useCapture是事件流,是否捕获
在IE8以及其以下版本中用
elementObj.attachEvent(type, handle)
function addEvent(obj, type, handle) {
try {
obj.addEventListener(type, handle, false);
} catch(e) {
try {
obj.attach('on' + type, handle);
} catch(e) {
obj['on' + type] = handle;
}
}
}
还没有评论,来说两句吧...