因為寫一個豐富Ajax的網站,JavaScript一定會寫很多,有時莫明奇妙的一個HtmlElement Bind二個事件函式以上,可能照成click一次,卻Post二次以上,原因是不同的地方呼叫初始化的函式,所以我就自己寫了一個Plugin去避免這個問題。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ( function ($) { //jquery object擴展 $.extend($.fn, { BindCheck: function (id, type, callback) { ///<summary>檢查有沒有重覆的id,沒有才Bind,如果沒有給id,就判斷有沒有重覆的type</summary> if (arguments.length == 2) { callback = type; type = id; if (!( this .data( "events" ) && this .data( "events" )[type])) { this .bind(type, callback); } } else { var bindCheck = $.data( this , "BindCheck" ) || $.data( this , "BindCheck" , {}) if (!bindCheck[id]) { this .bind(type, callback); bindCheck[id] = true ; } } } }); })(jQuery) |
範例
HTML:
1 2 | < input id="test1" type='button' value="test 1"/> < input id="test2" type='button' value="test 2"/> |
JS:
1 2 3 4 5 6 7 8 9 10 | $( function (){ $( "#test1" ).BindCheck( "click" , function (){ alert(1)}); $( "#test1" ).BindCheck( "click" , function (){ alert(2)}); $( "#test1" ).BindCheck( "click" , function (){ alert(3)}); $( "#test2" ).BindCheck( "test2-1" , "click" , function (){ alert(1)}); $( "#test2" ).BindCheck( "test2-1" , "click" , function (){ alert(2)}); $( "#test2" ).BindCheck( "test2-2" , "click" , function (){ alert(3)}); $( "#test2" ).BindCheck( "test2-2" , "click" , function (){ alert(4)}); }) |
說明
2-5是設定test1的click 事件函式,以type做區隔,一個type只會Bind一次,所以按下test1,只會 alert(1)
6-9是設定test2的click 事件函式,以id做區隔,一個id只會Bind一次,所以按下test2, 會alert(1)、alert(3)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?