<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
</head>
<body>
<button type="button" id="addBtn">给方框绑定事件</button>
<button type="button" id="remBtn">移除方框点击事件</button>
<br>
<br>
<div style="width: 200px; height: 200px; padding: 10px; border: 1px solid #ddd;" id="test">点击绑定\解绑按钮后再点击我,验证结果</div>
<br>
<br>
<br>
<br>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<div>111111111111111111111111</div>
<script>
(function() {
var doc = document;
var modern = doc.addEventListener;
var pre = modern ? '' : 'on';
//事件绑定
function on(ele, type, fn) {
var add = modern ? 'addEventListener' : 'attachEvent';
ele[add](pre + type, fn);
}
//事件解除
function off(ele, type, fn) {
var rem = modern ? 'removeEventListener' : 'detachEvent';
ele[rem](pre + type, fn);
}
//DOM加载
function ready(ele, fn) {
var rea = modern ? 'DOMContentLoaded' : 'readystatechange';
if (rea == 'readystatechange') {
ele[pre + rea] = function() {
if (ele.readyState == 'complete') {
fn();
}
};
} else {
window.on(ele, rea, fn);
}
}
window.on = on;
window.off = off;
window.ready = ready;
})();
function foo() {
alert('我绑定点击事件了');
}
//绑定
window.on(addBtn, 'click', function() {
window.on(test, 'click', foo);
});
//解除
window.on(remBtn, 'click', function() {
window.off(test, 'click', foo);
});
//DOM加载完成
window.ready(document, function() {
alert('dom加载完毕');
});
</script>
</body>
</html>
JavaScript事件绑定、事件解除、DOM加载完成,兼容IE8+
最新推荐文章于 2024-06-11 12:15:54 发布
本文介绍了一个简单的示例,展示了如何使用JavaScript为DOM元素绑定及解除点击事件。通过两个按钮实现事件的绑定和解除功能,适用于前端开发学习。
4360

被折叠的 条评论
为什么被折叠?



