当前位置:网站首页>DOM —— 事件绑定与解绑
DOM —— 事件绑定与解绑
2022-08-02 14:17:00 【z_小张同学】
概念:
事件,就是函数在某种状态下(是由浏览器设定的,也叫事件触发)被调用.JS捕捉到的发生在网页上的行为,然后执行提前设定好的程序,官方称为事件句柄,是交互体验的核心功能。
事件三要素
1.事件源
2.事件类型
3.事件处理程序(handler)
事件绑定的方式
(1)行内绑定方式:在标签行内 的事件值上写上标志"javaScript:后跟js代码"
<div class="box" onclick="console.log(666)">hello</div>
(2)元素属性绑定方式:兼容性很好,但是一个元素的同一个时间上只能绑定一个处理程序(handler)
var box = document.querySelector(".box")
box.onclick = function() {
console.log("hello world");
}
(3)给元素添加一个事件监听器:IE9以下不兼容,可以为一个事件绑定多个处理程序 (使用最多的方法)
var box = document.querySelector(".box")
box.addEventListener("click",function() {
console.log("hello");
})
(4)给元素添加一个事件监听器(IE专有):一个事件同样可以绑定多个处理程序
var box = document.querySelector(".box")
box.attachEvent("click",function() {
console.log("hello");
})
(5)多元素同事件同处理程序绑定方式(代理模式):父元素绑定事件 通过事件对象来区分用户触发的事件属于哪一个具体的对象
var box = document.querySelector(".box")
box.onclick=function(e) {
e.target
}
事件解绑
(1)行内和属性解绑的事件 box.onclick = null
var box = document.querySelector(".box")
box.onclick = function() {
box.onclick = null
}
(2)移除对应的元素的对应的监听程序
function fn() {
console.log(222);
}
var box = document.querySelector(".box")
box.addEventListener("click",fn)
// 解绑
box.removeEventListener("click",fn)
边栏推荐
猜你喜欢
Mysql索引优化二
转行软件测试,从零收入到月薪过万,人生迎来新转折
The relationship between base classes and derived classes [inheritance] / polymorphism and virtual functions / [inheritance and polymorphism] abstract classes and simple factories
Golang基础教程
【软件测试】selenium自动化测试1
打包项目上传到PyPI
Scala的基础语法(小试牛刀)
webrtc 数据接收流程图解
假的服务器日志(给history内容增加ip、用户等内容)
mongodb连接本地服务失败的问题
随机推荐
Mysql删库恢复数据
Template series-union set
代码细节带来的极致体验,ShardingSphere 5.1.0 性能提升密钥
OpenPose command line
The dynamic planning theory
【软件测试】selenium自动化测试2
ssm整合
移动端UI自动化相关环境配置
【软件测试】项目中关于测试人员的简单介绍
项目管理模块-项目权限功能开发
Apache ShardingSphere 5.1.2 发布|全新驱动 API + 云原生部署,打造高性能数据网关...
filebeat的配置
makefile——library
webrtc 中怎么根据 SDP 创建或关联底层的 socket 对象?
网络运维系列:二级域名启用与配置
Oauth2.0 authentication server construction
mongodb连接本地服务失败的问题
RTMP, RTSP, SRT 推流和拉流那些事
个人成长系列:好问题清单
Scala的基础语法(小试牛刀)