初始化后更新 jQuery 插件设置



我已经搜索了SO,但无法让我的插件正确更新。我在 init 时设置了插件选项,但之后我需要更改每个设置的值并重新运行插件。这是我到目前为止所拥有的:

(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>

您是否尝试过以与初始化相同的方式运行它?

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

您的插件并没有真正做任何对更新设置有用的事情,如果您想将 CSS 值重置为其他值,您只需使用其他值再次调用您的插件。

如果您确实有一个插件使用了可以更新的设置,则必须创建某种系统来检查第一个参数,并相应地设置设置等。

这有点接近jQuery UI在更新设置时的做法。

(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>

最新更新