分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

JS基础——事件操作总结

发布时间:2023-09-06 02:00责任编辑:蔡小小关键词:暂无标签

通用事件绑定

 
function bindEvent(elem,type,fn) {  elem.addEventListener(type,fn);}let a =document.getElementById(‘a‘);bindEvent(a,‘click‘,function(e){  e.preventDefault() //阻止浏览器默认行为,防止调转  alert(‘clicked’);}) 

事件冒泡

<body><div><p id ="p1">激活</p><p id ="p2">取消</p><p id ="p3">取消</p></div><div><p id ="p4">取消</p><p id ="p5">取消</p></div></body>
let body =document.bodylet p1 =document.getElementById(‘p1‘);bindEvent(p1,‘click‘,function(e){ ???e.stopPropagation(); //阻止事件冒泡 ???alert(‘激活‘)})bindEvent(body,‘click‘,function(e){ ???alert(‘取消‘)})

事件代理 

<body><div id="div1"><p id ="p1">激活</p><p id ="p2">取消</p><p id ="p3">确认</p></div></body>
let body =document.bodylet div1 =document.getElementById(‘div1‘);bindEvent(div1,‘click‘,function(e){ ???????const target =e.target; ???????if(target.nodeName === ‘A‘) { ?//判断是否是a标签alert(‘target.innerHTML‘)}}) 

事件绑定函数(完善)

function bindEvent(elem,type,selector,fn) {if(fn == null){fn = selector;selector = null;}elem.addEventListener(type,function(e){if(selector){const target= e.targetif(target.matches(seletor)){fn.call(target, e)}}else {fn(e);}});}

JS基础——事件操作总结

原文地址:https://www.cnblogs.com/fuGuy/p/9211214.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved