Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Question: is the element binding multiple events,
objects .addEventListener ( "event type", the event handler, false) method, Google and Firefox support, IE8 does not support
the object .attachEvent ( "have on the type of event," event handling function) method Google and Firefox support is not supported, IE8 support
Requirements: while allowing each browser support
Idea: package-compatible code to determine whether the browser supports
Specific codes are as follows:
<body>
<input type="button" value="按钮" id="btn"/>
</body>
<script>
/**
* //为任意的一个元素,绑定任意的一个事件
* @param element 任意的元素
* @param type 事件的类型,不加on进行传入
* @param fn 事件处理函数
*/
function addEventListener(element, type, fn) {
//判断浏览器是否支持这个方法
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
} else {
element["on" + type] = fn;
}
}
//测试
addEventListener(document.getElementById("btn"), "click", function () {
console.log("哈哈1");
});
addEventListener(document.getElementById("btn"), "click", function () {
console.log("哈哈2");
});
addEventListener(document.getElementById("btn"), "click", function () {
console.log("哈哈3");
});
</script>