2012-05-07 48 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更多信息。