0

私はいくつかのフィールドを持っています:

<div class="mystyle">
   <input name="font-size" value="12px" />
   <input name="font-family" value="Arial" />
   <input name="color" Value="#333" />

   <button class="setStyle">Save</button>
</div>

を使用していないことに注意してくださいform

ボタンをクリックすると、名前をスタイル属性として.setStyle使用inputし、値を属性値として使用します。

font-size:12px;
font-family:Arial;
color:#333;

を使用して、このスタイルをdivに割り当てます.css()

jQueryでこれを適切に行う方法を教えてください

私はこれを試しました:

jQuery('.setStyle').click(function(){
    var parent = jQuery(this).parent('.mystyle');

   // now run each inside parent for geting name and value
   // run a loop for setting CSS, if value is empty dont add style
}
4

3 に答える 3

3

デモ: http://jsfiddle.net/V3y4J/

var $target = $('.target');
$('.setStyle').click(function(){
    $('.mystyle > input').each(function(){
        $target.css(this.name, this.value);
    });
});

パフォーマンスを改善したい場合 (ただし、jQuery を使用するべきではありません)、次を使用することもできます。

デモ: http://jsfiddle.net/V3y4J/2/

var $target = $('.target'),
    $inputs = $('.mystyle > input'),
    applyStyles = function(){
        $target.css(this.name, this.value);
    };
$('.setStyle').click(function(){
    $inputs.each(applyStyles);
});
于 2013-07-15T14:48:36.693 に答える