代码之家  ›  专栏  ›  技术社区  ›  g5wx

初始化后更新jQuery插件设置

  •  2
  • g5wx  · 技术社区  · 8 年前

    我已经搜索了SO,无法正确更新我的插件。我在初始化时设置了插件选项,但之后需要更改每个设置的值,然后重新运行插件。以下是我目前掌握的情况:

    (function ($) {
        $.fn.testPlugin = function (options) {
        		// Default settings
            var settings = $.extend({
                padding: '0',
                margin: '0'
            }, options);
    
            return this.each(function () {
            	$(this).css({
              	'padding' : settings.padding,
                'margin' : settings.margin
              });
            });
        }
    }(jQuery));
    
    // Initialize the plugin
    $('#main').testPlugin({
      padding: '20px',
      margin: '20px 0'
    });
    
    // Update the plugin settings with new values and change the padding/margin on click
    $('#update').on('click', function() {
      var newPadding = $('#newPadding').val();
      var newMargin = $('#newMargin').val();
      console.log(newPadding, newMargin)
      
      // Here is where i'm stuck.
      // How to update the plugin settings and re-run it?
      
    })
    #main {
      width: 300px;
      background: #333;
      color: #fff;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="main">
      <p>Lorem ipsum dummy text</p>
    </div>
    
    <input type="text" id="newPadding" value="20px" />
    <input type="text" id="newMargin" value="20px 0" />
    <button id="update">Update</button>
    2 回复  |  直到 8 年前
        1
  •  1
  •   jidexl21    8 年前

    你试过用初始化的方法运行它吗?

    $('#main').testPlugin({
      padding: newPadding,
      margin: newMargin
    });
    
        2
  •  1
  •   adeneo    8 年前

    如果你确实有一个插件使用了一些可以更新的设置,那么你必须创建某种系统,在其中检查第一个参数,并相应地设置设置等。

    (function($) {
      $.fn.testPlugin = function(options, value) {
        if (typeof options === 'string' && value) {
          this.data(options, value);
        } else {
          var opts = $.extend({
        		text: 'This is a default text !'
      		}, options);
    
          return this.each(function() {
            $(this).on('click', function() {
              console.log($(this).data('text'));
            })
          }).data(opts);
        }
      }
    }(jQuery));
    /* ------------------------------- */
    // Initialize the plugin
    $('#main').testPlugin({
      text: 'This works just fine'
    });
    
    // change the setting
    $('#change').on('click', function() {
      $('#main').testPlugin('text', 'So does this !');
      /*  ----  */
      $(this).css('color', 'red');
      $('#main').text('Click me again!');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="main">Click me !</div>
    <br />
    <br />
    <br />
    <button id="change">Now change the text</button>