如何编写自己的自定义jQuery插件(Uncaught TypeError:...不是函数)

时间:2015-08-28 15:25:08

标签: jquery jquery-plugins syntax-error

我在哪里弄错了?那是一些语法错误吗?

custom.js:

(function($){
    $.fn.marquee = function(options, callback){

        // check callback
        if(typeof callback == 'function'){
            callback.call(this);
        } else{
            console.log("secound argumnt (callback) is not a function");
            throw "callback must be a function";
            return;
        }

        //set and overwrite default options
        var defOptions = $.extend({
            option1: 10,
            option2: 'something'
        }, options);
    };

    //plugin logic here
    // ...

    return this;

}(jQuery));
//END PLUGIN

现在我在同一个文件中尝试通过调用

来运行插件
// RUN PLUGIN with options or leave empty for defeaults
$.marquee({
    option1: 9,
    option2: 'something else'
}, function(){
    alert('some callback');
});

然后我得到这个错误(在chrome控制台中)......谁知道这里的问题是什么?:

Uncaught TypeError: $.marquee is not a function

有关Chrome控制台错误的更多详细信息:

(anonymous function) @ custom.js:25m.
Callbacks.j @ jquery-1.11.2.min.js:2m.
Callbacks.k.fireWith @ jquery-1.11.2.min.js:2m.
extend.ready @ jquery-1.11.2.min.js:2J @ jquery-1.11.2.min.js:2

1 个答案:

答案 0 :(得分:1)

那是因为你已将它附加到jQuery的原型$.fn。如果您的代码已经

,您的插件将正常工作
$('some element').marquee({
    option1: 9,
    option2: 'something else'
}, function(){
    alert('some callback');
});

$.fn处声明的插件是适用于元素的插件,并且在插件中引用了this

修复方法是在$jQuery

上声明
$.marquee = function { 
    // (...) Code here
}
相关问题