js以类似jquery的模式绑定事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button class="a"></button> </body> </html> <script> var $ = function (el) { return new _$(el); }; var _$ = function (el) { this.el = (el && el.nodeType == 1) ? el : document; }; _$.prototype = { constructor: _$, addEvent: function (type, fn, capture) { var el = this.el; if (window.addEventListener) { el.addEventListener(type, fn, capture); var ev = document.createEvent("HTMLEvents"); ev.initEvent(type, capture || false, false); // 在元素上存储创建的事件,方便自定义触发 if (!el["ev" + type]) { el["ev" + type] = ev; } } else if (window.attachEvent) { el.attachEvent("on" + type, fn); if (isNaN(el["cu" + type])) { // 自定义属性,触发事件用 el["cu" + type] = 0; } var fnEv = function (event) { if (event.propertyName == "cu" + type) { fn.call(el); } }; el.attachEvent("onpropertychange", fnEv); // 在元素上存储绑定的propertychange事件,方便删除 if (!el["ev" + type]) { el["ev" + type] = [fnEv]; } else { el["ev" + type].push(fnEv); } } return this; }, fireEvent: function (type) { var el = this.el; if (typeof type === "string") { if (document.dispatchEvent) { if (el["ev" + type]) { el.dispatchEvent(el["ev" + type]); } } else if (document.attachEvent) { // 改变对应自定义属性,触发自定义事件 el["cu" + type]++; } } return this; }, removeEvent: function (type, fn, capture) { var el = this.el; if (window.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else if (document.attachEvent) { el.detachEvent("on" + type, fn); var arrEv = el["ev" + type]; if (arrEv instanceof Array) { for (var i = 0; i < arrEv.length; i += 1) { // 删除该方法名下所有绑定的propertychange事件 el.detachEvent("onpropertychange", arrEv[i]); } } } return this; } }; var dom = document.querySelector(".a"); var test = $(dom).addEvent("alert", function () { alert("弹弹弹,弹走鱼尾纹~~"); }, false); test.fireEvent("alert"); </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2016-11-17 iis6.0报以下的错。。
2016-11-17 注册asp.net
2016-11-17 往linux上传、下载
2016-11-17 win2003 Enterprise Edition sp2 企业版序列号
2016-11-17 vscode中启动浏览器的tasks.json
2015-11-17 Json.net 时间格式处理
2015-11-17 js中以键值对的形式当枚举