简体   繁体   English

jQuery插件回调无法正常工作

[英]jQuery Plugin callback doesn't work properly

I replicate the problem in simple plugin in jsfiddle: https://jsfiddle.net/5atn3010/1/ 我将问题复制到jsfiddle中的简单插件中: https ://jsfiddle.net/5atn3010/1/

The idea is: 这个想法是:

  • I have 2 selectors with a range of years (from 2005 to 2020) 我有2个选择器,范围不同(从2005年到2020年)
  • When I select an option in the first selector, the selected value (for example 2010) is set in the second selector as the minimum value. 当我在第一个选择器中选择一个选项时,所选值(例如2010)在第二个选择器中设置为最小值。
  • Finally the second selector is redrawn and only shows the new values (form 2010 to 2020) 最后,重新绘制第二个选择器,并且仅显示新值(从2010到2020)

This works, but with a big mistake. 这可行,但是有一个大错误。 Not only changes the second select values, but the minimum value for the first selector also changes. 不仅改变第二选择值,而且第一选择器的最小值也改变。

Why does it happen? 为什么会发生? How can I solve it? 我该如何解决?

;(function ( $, window, document, undefined ) {

    "use strict";

    var pluginName = "testing";

    function Plugin( element, options ) {

        this.element = element;
        this.$element = $(element);
        this.name = pluginName;

        this.opts = $.extend({}, $.fn[pluginName].defaults, options);

        this.$elements = {
            year:null,
        }

        this.init(element,options);

    }


    Plugin.prototype =  {

        init: function () {
            var me=this;

            me.$elements.year=$("<select />").attr("name","year");
            if (me.opts.css!=null) {
                me.$elements.year.addClass(me.opts.css);
            }

            me.$elements.year.on("change",function() {
                me.opts.onChange.call(me,me.$elements.year.val());
                me._draw.call(me); //redraw me only for show error
            });

            me.$element.append(me.$elements.year);

            me._draw();
        },

        _draw: function() {
            var me=this;

            var date_start=me.opts.date.start;
            var date_end=me.opts.date.end;

            me.$elements.year.find("option").remove();
            for (var i=date_start;i<=date_end;i++) {
                var option=$("<option/>").attr("value",i).text(i);
                me.$elements.year.append(option);
            }
        },

        setMin: function(min) {
            this.opts.date.start=min;
            this._draw();
        }

    }


    $.fn[pluginName] = function(options) {
        var param=arguments[1];
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
            else if ($.isFunction(Plugin.prototype[options])) {
                $.data(this, 'plugin_' + pluginName)[options](param);
            } else {
                $.error('Method ' + options + ' is not available');
            }
        });
    };

    $.fn[pluginName].defaults = {
        date: {
            start:2005,
            end:2020
        },
        onSelect:function() {}
    };


})( jQuery, window, document );

$().ready(function(){
   $("#span1").testing({
       onChange:function(min) {
           console.log(min);
            $("#span2").testing("setMin",min);
       }
   });
   $("#span2").testing();
});

there are two issues with your code. 您的代码有两个问题。 First of all - you're not extending your options object recursively. 首先-您不会递归扩展您的options对象。 To be short - you have two different opts objects that holds a reference to the same date object. 简而言之-您有两个不同的opts对象,这些对象包含对同一date对象的引用。 I added some logging so you can understand what I'm talking about. 我添加了一些日志记录,以便您了解我在说什么。 You need to deep copy your options object. 您需要深度复制选项对象。

Please, read carefully jQuery.extends page http://api.jquery.com/jquery.extend/ 请仔细阅读jQuery.extends页面http://api.jquery.com/jquery.extend/

Secondly, you assign this.opts.date.start to a <option> value. 其次,将this.opts.date.start分配给<option>值。 It works okay for now but it won't work as expected if you will try to set a minimum date to selected date + N . 现在它可以正常工作,但是如果您尝试将最小日期设置为selected date + N则它将无法正常工作。 It will concatenate N as a string instead of adding. 它将N连接为字符串而不是添加。 I added some logs for this case as well. 我也为这种情况添加了一些日志。

http://jsfiddle.net/5atn3010/7/ http://jsfiddle.net/5atn3010/7/

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

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