2012-01-11 22 views
0

考慮這個功能:創造我自己的功能,將使用和不使用jQuery選擇工作

jQuery.fn.MyFunction = function (event) { 
    alert(this.text()); 
} 

我想它調用方法有兩種:

$('#myElement').bind('click', MyFunction); 

$("#myOtherElement").click(function (event) { 
    //some processing 
    this.MyFunction(event); 
} 

宣佈myFuntion支持這兩種情況的正確方法是什麼?

這裏是jsfiddle http://jsfiddle.net/4Z4fQ/5/,但我似乎有綁定到我的開始按鈕jsfiddle問題也。

回答

2

這是一個jsfiddle它的工作。

您所遇到的主要問題是,你永遠不會加入你的右括號當您單擊事件綁定到myOtherElement

的Html

<div id='myElement'> 
    My Element 
</div> 
<div id='myOtherElement'> 
    My Other Element 
</div> 

JS

jQuery.fn.MyFunction = function (event) { 
    alert('My function was called'); 
    alert($(this).text()); 
}; 

$('#myElement').bind('click', $.fn.MyFunction); 
$("#myOtherElement").click(function (event) { 
    //some processing 

    $(this).MyFunction(event); 
}); 
相關問題