jQuery-从输入中获取值,然后将其设置为样式
我有一些领域:jQuery-从输入中获取值,然后将其设置为样式,jquery,css,Jquery,Css,我有一些领域: <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>
<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>
现在使用.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
}
你可以做:
$(".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]);
}
});
$(“.setStyle”)。单击(函数(){
var attributes=$(this.sibbines(“input”).map(function(){
如果(this.value!='')返回this.name+,“+this.value
}).get();
对于(变量i=0;i
演示:您可以执行以下操作:
$(".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]);
}
});
$(“.setStyle”)。单击(函数(){
var attributes=$(this.sibbines(“input”).map(function(){
如果(this.value!='')返回this.name+,“+this.value
}).get();
对于(变量i=0;i
演示:您可以使用以下jQuery代码:
$('.setStyle').click(function(){
button = $(this)
button.removeAttr('style')
$('.mystyle input').each(function() {
button.css({$(this).attr('name'): $(this).val()})
})
})
您可以使用以下jQuery代码:
$('.setStyle').click(function(){
button = $(this)
button.removeAttr('style')
$('.mystyle input').each(function() {
button.css({$(this).attr('name'): $(this).val()})
})
})
演示:
如果您想提高性能(但不应该使用jQuery),也可以使用
演示:
演示:
如果您想提高性能(但不应该使用jQuery),也可以使用
演示:
您是否尝试过编写一些jQuery脚本来实现这一点?如果是这样,请发布它。您是否尝试过编写一些jQuery脚本来实现这一点?如果是,请张贴。您应该考虑
s的顺序。如果标记发生变化,这将非常失败。@Dogbert——是的……是的,这将失败。给我一分钟,让这更好。感谢回答和小提琴,但如何不添加属性名称,如果输入值为空?谢谢我会检查it@HowToPlease--我会使用下面的Oriols答案,它更干净,只需在那里添加空值的检查。您应该考虑
s的顺序。如果标记发生变化,这将非常失败。@Dogbert——是的……是的,这将失败。给我一分钟,让这更好。感谢回答和小提琴,但如何不添加属性名称,如果输入值为空?谢谢我会检查it@HowToPlease--我会使用下面的Oriols答案,它更干净,只需在那里添加空值的检查。
var $target = $('.target'),
$inputs = $('.mystyle > input'),
applyStyles = function(){
$target.css(this.name, this.value);
};
$('.setStyle').click(function(){
$inputs.each(applyStyles);
});