js如何避免重复监听addEventListener事件?

js 重复 编程技术
发布日期 2023-08-30 更新日期 2023-08-30 阅读次数 182 文章字数 387

要避免重复监听

办法一、指定一个元素和事件,这时重复添加只有一个生效

const $btn = document.getElementById('btn');

const clickHandler = () => {
	console.info('this is handler1')
};

// 多次添加同一个事件处理函数,则不会重复执行
$btn.addEventListener('click', clickHandler);
$btn.addEventListener('click', clickHandler);

办法二、对于全局的,没法指定某个元素,最好的办法是先remote,然后再add,也就是在每次添加前先试着删除

例子:

//esc
document.removeEventListener("keydown",app.escShadowCloseHandler);
document.addEventListener("keydown",app.escShadowCloseHandler);

文章作者: 朱丰华

文章链接: https://smart.52dixiaowo.com/blog/post-488.html

版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。

js 重复

发表评论

相关推荐
朱丰华   |   3周前   |   对象 · 属性 · 反射 · js

js 对象反射 Reflect

43    评论    点赞
朱丰华   |   1年前   |   页面 · 监听

iframe子父页面信息传递与监听

483    评论    点赞
朱丰华   |   1年前   |   请求 · 一个

ab测压命令,apache测压工具

219    评论    点赞
朱丰华   |   1年前   |   < · iframe

让iframe嵌入的视频自适应 (100%宽度)?

162    评论    点赞
朱丰华   |   1年前   |   下载 · 请求

idm、浏览器下载发送两次下载请求

203    评论    点赞
朱丰华   |   1年前   |   html · id · <

html同一个页面有两个相同id ,如何用id选择器选中

139    评论    点赞
朱丰华   |   1年前   |   php

windows下编写、编译php扩展

201    评论    点赞
朱丰华   |   1年前   |   js · export · import

js es6 export,import,export default的用法和区别

153    评论    点赞
朱丰华   |   1年前   |   js · vue · 监听

js vue监听,深度监听

137    评论    点赞
朱丰华   |   1年前   |   vue · model

vue语法v-model原理与实现

145    评论    点赞
朱丰华   |   1年前   |   javascript · js · obfuscator · 混淆

javascript-obfuscator混淆js文件

74    评论    点赞
朱丰华   |   1年前   |   js · vue · npm · 安装

npm快速上手

148    评论    点赞
朱丰华   |   1年前   |   js · 模块 · nodejs

nodejs引入自定义模块

75    评论    点赞
朱丰华   |   1年前   |   nvm · git · 安装

entos7安装、使用nvm

100    评论    点赞
朱丰华   |   1年前   |   js · 滚动 · html

原生js实现顶部进度条效果

78    评论    点赞
朱丰华   |   1年前   |   python · linux · www

linux给www用户【非root】安装python3

242    评论    点赞
朱丰华   |   1年前   |   js · php · 字符 · 字符串

php json_encode对字符串转义用法

163    评论    点赞
朱丰华   |   1年前   |   文件 · c语言 · include

C语言include语法,h文件和c文件的关系

124    评论    点赞
朱丰华   |   1年前   |   zend · php · 字符串 · _string

php扩展zend_string类型与char类型转换

123    评论    点赞
朱丰华   |   2年前   |   api

api接口的参数"原子"设计

102    评论    点赞
{{item.author_name}}   |   {{new Date(item.date*1000).log()}}   |   {{it}} ·

{{item.title}}

{{item.uv}}    评论    点赞