JavaScript自带的addEventListener和removeEventListener方法是不允许事件绑定的函数携带参数的,通过查询找到了一个解决方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">按钮</button>
<script>
/**
* 监听事件绑定
* @param {Object} dom 要绑定监听事件的dom对象
* @param {String} type 事件类型
* @param {Function} fn 事件函数
* @param {*} parms 事件函数参数
* @param {Boolean} capture 是否是事件捕获(默认为事件冒泡)
*/
const addEvent = (dom, type, fn, parms, capture = false) => {
dom['e' + type + fn] = dom['e' + type + fn] || null
if (!dom['e' + type + fn]) {
dom['e' + type + fn] = event => {
let e = event || window.event
e.parms = parms || {}
fn.call(dom, e)
}
}
dom.addEventListener(type, dom['e' + type + fn], capture)
}
/**
* 监听事件移除
* @param {Object} dom 要绑定监听事件的dom对象
* @param {String} type 事件类型
* @param {Function} fn 事件函数
* @param {Boolean} capture 是否是事件捕获(需要和绑定事件capture一致,默认为事件冒泡)
*/
const removeEvent = (dom, type, fn, capture = false) => {
dom.removeEventListener(type, dom['e' + type + fn], capture);
}
/*-------示例-------*/
const btn = document.querySelector('#btn')
// 事件函数(2秒之后自动移除事件监听)
const fun = parms => {
//打印携带的参数
console.log('携带参数:' + parms.parms)
setTimeout(() => {
removeEvent(btn, 'click', fun)
}, 2000)
}
addEvent(btn, 'click', fun, '123')
</script>
</body>
</html>
网友评论