简体   繁体   English

编写jQuery插件,它没有执行

[英]Writing jquery plugin and it is not executing

I am trying to write a simple jQuery plugin for my needs, using a variant of the first one in this style guide . 我正在尝试使用本样式指南中第一个jQuery的变体来满足我的需要,编写一个简单的jQuery插件。

;(function($) {
    var plugin_name = 'my_plugin',
        defaults = {};

    function Plugin ( element, options ) {
        this.element = element;

        this.options = $.extend( {}, defaults, options );

        this._defaults = defaults;
        this._name = plugin_name;

        this.init();
    }

    Plugin.prototype = {
        init: function () {
            // Plugin code - attempt to debug
            alert('hi');
        }
    }

    $.fn[plugin_name] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + plugin_name)) {
                $.data(this, 'plugin_' + plugin_name, new Plugin( this, options ));
            }
        })
    }

})( jQuery );

However, it doesn't seem to be executed when I call it. 但是,在我调用它时似乎没有执行。 Fiddle here: http://jsfiddle.net/DCRnU/ 在这里提琴: http : //jsfiddle.net/DCRnU/

$(document).ready(function() {
    $.fn.my_plugin();
});

What am I missing out on? 我错过了什么?

You're not calling the function properly. 您没有正确调用该函数。
If you had a div element in your HTML, you could call your function like this: 如果您的HTML中有一个div元素,则可以这样调用函数:

$(document).ready(function() {
  $("div").my_plugin();
});

Example fiddle 小提琴的例子

That's because this line: return this.each 那是因为这行: return this.each

It's expect to get some iterable object. 期望得到一些可迭代的对象。 But there is nothing to loop over it. 但是没有什么可以循环的。

if you add something like this: 如果添加以下内容:

var array = [1];
$(array).my_plugin();

it'll be fine. 会没事的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM