2017-08-03 14 views
2

私はSOを検索して、マインプラグインを正しく更新することができません。 initでプラグインオプションを設定しましたが、後で各設定の値を変更してプラグインを再実行する必要があります。ここで私はこれまで持っているものです。initの後に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のUIはそれをしない方法にやや近いです! – g5wx

1

本当にあなたが何か他のものへのCSSの値をリセットしたい場合は、更新された設定のための任意の使用を持っているでしょう何もしないあなたのプラグインは、あなたは自分のプラグインいくつかの他の値との1より多くの時間を呼びたいです。

あなたは、彼らが更新される可能性が何かの設定を使用するプラグインを持っていた場合は、最初の引数がチェックされているシステムのいくつかの並べ替えを作成する必要があるだろう、との設定は、それに応じて設定など

あなたが設定

(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

関連する問題