2012-05-07 50 views
1

我非常想知道可能導致函數「不在」的原因是什麼。
例如,我有以下幾點:

$.fn.myfunction = function(options){ 
    alert("test"); 
}; 
    $("#hello").myfunction(); 
alert($.fn.myfunction instanceof Function); 

爲什麼會螢火,日誌,這是不是一個功能?

在此先感謝。

編輯:
我想那可能是錯誤原因的所有可能的列表。 這不是我得到的錯誤,但我只想擴大我的視野,並意識到更多的可能性。

+0

'$('x')。myfunction'中的$''可能是'$ .fn.myfunction'中的另一個函數,而不是'$'。 –

+0

記錄哪些功能不在哪裏?請提供更多信息。 – Ashe

+0

jQuery已經被加載了嗎? –

回答

5

設置$.fn.myfunction使得myfunction函數可用於由$(selector)返回的對象,而不是$本身。

因此,$("#hello").myfunction是一個函數,但$.myfunction不是。如果你真的想$.myfunction是出於某種原因時(例如,它並不需要一個jQuery對象列表操作效用函數),只需將它設置明確,不使用$.fn

$.myfunction = function() { .... } 
+2

這是['.each()'](http://api.jquery.com/each/)和['$ .each()'](http://api.jquery.com/jQuery)之間的區別。每/)。兩者都是完全不同的功能。 –

+0

這是一篇很好的文章,詳細解釋了這個問題:http://asimilia.wordpress.com/2008/12/17/jquery-extend-confusion/ –

1

添加括號似乎工作:

alert($().myfunction instanceof Function); 

返回true。

2

是什麼$在上下文中?也許jQuery?如果您使用的是jQuery,請標記您的問題。

(function($) { 
    $.fn.myPlugin = function() { 

    return this.each(function() { // Maintaining chainability 

     var $this = $(this); 

     // Do your awesome plugin stuff here 
     console.log($this); // TEMP 

    }); 

    }; 
})(jQuery); 

用法:$('#hello').myPlugin();

查看關於jQuery plugin authoring更多信息。