0
好吧,我已经尝试了5个不同的版本,我很确定我的代码越来越差了,所以我想我应该停下来寻求帮助。。每个属性
这里就是我想要做的事:
在HTML,可以说我创建这个按钮:
<button border="#ff0000" bg="#0000ff" color="#fff" pad="10px">Click Me</button>
正如你所看到的,我做了几个属性,并给他们每人一值。
我想使用jquery来选择每个按钮,并且对于每个按钮,遍历每个属性并获取该值并添加具有该值的真实属性。
例如,它会看到border =“#ff0000”并创建边框颜色:#ff0000:CSS属性并将其附加到该按钮。它会看到bg =“#0000ff”属性并附加背景颜色:#0000ff:该按钮。
这里是我的垃圾:
$(document).ready(function() {
$("button").each(function() { // selects all buttons
$(this.attr).each(function() { // selects all attributes within each button
var attribute = this.parent().attr(); // sets a variable that is equal to the value of the selected made up attribute
if ($(this).parent().attr("border")) { // if there is an attribute called border, do this
$(this).parent().css("border-color", attribute) // give this attribute's parent (the button) this css attribute
} else if ($(this).attr("bg")) { // rinse and repeat for each attribute I made up
$(this).parent().css("background-color", attribute)
} else if ($(this).attr("color")) {
$(this).parent().css("color", attribute)
}
});
});
});
请让我知道,如果我没有做任何意义=]
UPDATE
下面的代码的作品,但我做不到帮助感觉有一个更简单/更短的方式来编码,因为你可以看到我重复了相同的代码。
$(document).ready(function() {
$("button").each(function() {
var bg = $(this).attr("bg");
var border = $(this).attr("border");
var color = $(this).attr("color");
var radius = $(this).attr("radius");
var pad = $(this).attr("pad");
if($(this).attr("bg")) {
$(this).css("background", bg)
}
if($(this).attr("border")) {
$(this).css("border-color", border)
}
if($(this).attr("color")) {
$(this).css("color", color)
}
if($(this).attr("radius")) {
$(this).css("border-radius", radius)
}
if($(this).attr("pad")) {
$(this).css("padding", pad)
}
});
});