2017-08-03 73 views
2

我已经搜索过了,无法让我的插件正确更新。我在初始化时设置了插件选项,但是之后我需要更改每个设置的值并重新运行插件。以下是我迄今为止:在初始化后更新jQuery插件设置

(function ($) { 
 
    $.fn.testPlugin = function (options) { 
 
    \t \t // Default settings 
 
     var settings = $.extend({ 
 
      padding: '0', 
 
      margin: '0' 
 
     }, options); 
 

 
     return this.each(function() { 
 
     \t $(this).css({ 
 
      \t '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>

回答

1

你尝试运行它,你初始化它以同样的方式?

$('#main').testPlugin({ 
    padding: newPadding, 
    margin: newMargin 
}); 
+0

我不这样想:)谢谢这有点接近jQuery用户界面是如何做的! – g5wx

1

您的插件并没有真正做任何事情,会有什么用更新的设置,如果你想重置CSS值到别的东西,你只需要调用插件更多的时间与其他一些价值观。

如果您确实有使用,他们可以被更新的东西设置的插件,你必须建立某种形式的系统,其中第一个参数被选中,并设置相应的设置等

当你更新设置

(function($) { 
 
    $.fn.testPlugin = function(options, value) { 
 
    if (typeof options === 'string' && value) { 
 
     this.data(options, value); 
 
    } else { 
 
     var opts = $.extend({ 
 
    \t \t text: 'This is a default text !' 
 
    \t \t }, 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>

+0

感谢您的详细解释,+1。 – g5wx