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 回答
1

你可以做:

$(".setStyle").click(function() {
    var attributes = $(this).siblings("input").map(function() {
        if (this.value != '') return this.name + "," + this.value
    }).get();

    for (var i = 0; i < attributes.length; i++) {
        $("#styleDiv").css(attributes[i].split(",")[0], attributes[i].split(",")[1]);
    }

});

演示:http: //jsfiddle.net/Za77A/3/

于 2013-07-15T14:45:19.070 回答
0

你可以使用这个 jQuery 代码:

$('.setStyle').click(function(){
    button = $(this)
    button.removeAttr('style')
    $('.mystyle input').each(function() {
        button.css({$(this).attr('name'): $(this).val()})
    })
})
于 2013-07-15T14:45:42.020 回答