【问题标题】:jQuery Plugin Stored ValuesjQuery 插件存储值
【发布时间】:2012-04-19 15:30:15
【问题描述】:

我正在开发一个 jquery 插件,但在保存属性以供以后使用时遇到了问题。在下面的示例中,当我在寻找18, 50, 18 时,控制台输出为18, 50, 50。我理解为什么会发生这种情况,但我想不出一个保存properties 以用于多种不同方法的好方法。我有一种感觉,我错过了一些非常明显的东西,但我只是没有看到它。

<html>
    <body>
        <h1>Hello</h1>
        <h2>World</h2>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
        <script type="text/javascript">
            (function ($) {
                var commonOperations, methods, properties;

                commonOperations = function () {
                    console.log(properties.height);
                };

                methods = {
                    init : function (overrides) {
                        var defaults;
                        defaults = { height: 18 };
                        properties = $.extend(defaults, overrides);

                        commonOperations();
                    },

                    foo : function () {
                        commonOperations();
                    }
                };

                $.fn.myPlugin = 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 for jQuery.myPlugin');
                    }
                };
            }(jQuery));

            $(document).ready(function () {
                $("h1").myPlugin();
                $("h2").myPlugin({ height: 50 });
                $("h1").myPlugin("foo");
            });
        </script>
    </body>
</html>

【问题讨论】:

    标签: javascript jquery jquery-plugins closures


    【解决方案1】:

    这取决于您的插件的性质,但使用.data() 来存储每个元素的属性可能是有意义的。

       init: function(overrides) {
         return this.each(function() {
           var defaults = { whatever: "foo" };
           $(this).data('properties', $.extend(defaults, overrides));
         });
       }
    

    那么其他方法总是从元素中拉取“属性”对象:

        foo : function () {
          return this.each(function() {
            commonOperations.call(this, $(this).data('properties'));
          });
        }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多