2

我正在尝试创建我的第一个 jQuery 插件,阅读jQuery 插件创作,它真正强调的一件事是使用方法而不是命名空间。我还尝试使用该指南中的数据在方法之间反弹变量,但它不起作用。我需要创建一些数据,将其传递给另一个方法来更新它并将其发送到其他地方。

(function($) {

    var methods = {
        init : function(settings) {

            return this.each(function(){

                var x = 3; 
                var object = $(this);

                // Bind variables to object
                $.data(object, 'x', x);

                $(object).bbslider('infoParse');

                var y = $.data(object,'y');
                alert(y);

            }); // End object loop

        }, // End init
        infoParse : function() { 
            var object = $(this);
            var x = $.data(object,'x');

            alert(x);

            var y = 10;
            $.data(object,'y',y);
        }, // End infoParse
    }; // End method


    $.fn.bbslider = function(method) {

        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.bbslider' );
        }       
    }; // End slider

})(jQuery); 

这是一个 jsFiddle 来说明我的意思:http: //jsfiddle.net/wRxsX/3/

如何在方法之间传递变量?

4

1 回答 1

2

看看这个http://jsfiddle.net/wRxsX/6/是否可以?

element.data(k,v)

$.data 应该在元素上使用

http://api.jquery.com/data/

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

于 2013-01-26T04:09:05.740 回答