惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
WordPress大学
WordPress大学
GbyAI
GbyAI
C
Check Point Blog
M
MIT News - Artificial intelligence
T
The Blog of Author Tim Ferriss
Jina AI
Jina AI
博客园 - 【当耐特】
U
Unit 42
月光博客
月光博客
腾讯CDC
Y
Y Combinator Blog
小众软件
小众软件
博客园_首页
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
博客园 - 聂微东
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
T
Tailwind CSS Blog

博客园 - 黃偉榮

Web Project的檔案共用小技巧 IoC的中繼器:CommonServiceLocator UTF8Encoding與BOM Temporary Post Used For Theme Detection (d4b0aefa-c88e-4957-bba7-b367d1bfa042 - 3bfe001a-32de-4114-a6b4-4005b770f6d7) 寫CodedUI時如何尋找控制項的小技巧 Visual Studio 2010 Feature Packs 2之Silverlight自動化測試 Moles - Isolation framework for .NET(假.Net)介紹 [小技巧]Entity Framework強型別Include C#仿Oracle Decode,將ValueType對應成String - 黃偉榮 - 博客园 Visual Studio 單元測試的3種Initialize與Cleanup jQuery套件-檢查頁面的欄位是否有變更 用EventLogReader查詢特殊EventLog ASP.NET MVC TempData使用心得 Visual Stuiod 自訂檔案比較合并工具 [小技巧]自動化測試時NLog的訊息輸出到測試結果中 小技巧:專案切換32與64位元組件 Linq小技巧:日期處理 Unit Test小技巧 : DateTime的Stub 解決TFS Build Asp.Net Mvc開啟MvcBuildViews後無法載入組件問題
jQuery自製Plugin-Bind事件函式時檢查有沒有Bind過
黃偉榮 · 2010-10-20 · via 博客园 - 黃偉榮

因為寫一個豐富Ajax的網站,JavaScript一定會寫很多,有時莫明奇妙的一個HtmlElement Bind二個事件函式以上,可能照成click一次,卻Post二次以上,原因是不同的地方呼叫初始化的函式,所以我就自己寫了一個Plugin去避免這個問題。

(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:

<input id="test1" type='button' value="test 1"/>
<input id="test2" type='button' value="test 2"/>

JS:

$(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)