2013-08-01 105 views
5

我在學習jquery自定義事件。jquery中的簡單自定義事件

我需要在頁面加載時觸發一個簡單事件。

HTML:

<div id="mydiv"> my div</div> 

我需要調用我自己的事件,火災警報

$("#mydiv").custom(); 

我嘗試下面的代碼。

function customfun() 
    { 
     $("#mydiv").trigger("custom"); 
    } 

    $(document).ready(function() { 

     $("#mydiv").bind(customfun, function() { 
      alert('Banana!!!'); 
     }); 

    }); 
+0

bind()期望參數1是字符串或對象,而不是函數。 – Virus721

回答

2

要調用自定義事件,因爲你需要jQuery的功能,以及通過$.fn定義這樣的功能:

$(document).ready(function() { 
    //define the event 
    $(document).on('custom', function() { 
     alert('Custom event!'); 
    }); 

    //define the function to trigger the event (notice "the jquery way" of returning "this" to support chaining) 
    $.fn.custom = function(){ 
     this.trigger("custom"); 
     return this; 
    }; 

    //trigger the event when clicked on the div 
    $("#mydiv").on("click", function() { 
     $(this).custom(); 
    }); 
}); 
4

您需要綁定到相同的事件名稱 - 「custom」 - 與您觸發的名稱相同。就像這樣:

$("#mydiv").on("custom", function() { ... 

Fiddle

+2

'.on()'是下一個'.bind()'.. :) :) – bipen

+0

感謝您的回答。我在一些代碼示例中看到,人們使用$(「#mydiv」)。customevent();除了內置的clickevnts ..等等。所以我怎麼稱呼那種事件呢? – chamara

0

你可以通過這樣稱呼它:

$.fn.mycustom = function(){ 
    return this; 
}; 

$("div").mycustom();