javascript jquery 插件未捕获的类型错误:对象不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11191033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery plugin Uncaught TypeError: object is not a function
提问by Mina Gabriel
I just created my first jQuery plugin
, it is very simple it slideToggle
two Divs
, the code works fine and it do what i want , the problem is that i get an ERROR
message at the console saying :
我刚刚创建了我的第一个jQuery plugin
,它非常简单,slideToggle
两个Divs
,代码工作正常并且可以满足我的要求,问题是我ERROR
在控制台收到一条消息:
Uncaught TypeError: object is not a function
it refer to this line of code
它指的是这行代码
})(jQuery);
CODE
代码
$(function($) {
$.fn.toggleDiv = function(opt) {
var options = $.extend({}, $.fn.toggleDiv.objectOptions, opt);
return this.each(function() {
if (options.animation == true) {
$(this).slideToggle();
} else {
$(this).toggle();
}
});
};
$.fn.toggleDiv.objectOptions = {
animation: false
};
$("button").click(function() { $("#Div1, #Div2")
.toggleDiv({animation : fa}); return false; });
})(jQuery);
Does any one know what is that error and how can i fix it thanks
有谁知道那个错误是什么,我该如何解决,谢谢
回答by Searle
You either want to do
你要么想做
(function ($) { ... })(jQuery);
if you want your code to be run immediatly,
如果您希望您的代码立即运行,
or
或者
jQuery(function ($) { .... });
for your code to be run on document-ready.
让您的代码在文档就绪时运行。
You are referring to $("button"), and therefore need the document tree to be available. So use the second version. A even nicer solution would be to use the jQuery function "delegate", this would look something like this:
您指的是 $("button"),因此需要文档树可用。所以使用第二个版本。一个更好的解决方案是使用 jQuery 函数“delegate”,它看起来像这样:
jQuery(function ($) {
$(document).delegate("button", "click", function (ev) { ... });
});