这是一个想法,拉出从SQL提供的颜色十六进制代码并注入到这些列表项中的span中,然后使用这些十六进制代码来设置它所在的跨度的背景颜色。我能够得到正确的信息到数组但我不知道如何使用该数组以正确的顺序设置backgroundColor规则。
<ul id="color-hr">
<li id="hr-aqua">
<a href="Javascript:"><span></span></a>
<ul>
<li><a href="Javascript:"><span>70859a</span> Jetstream</a></li>
<li><a href="Javascript:"><span>4d98b5</span> Periwinkle</a></li>
<li><a href="Javascript:"><span>5ecfcc</span> Deep Caribean</a></li>
<li><a href="Javascript:"><span>b6d8d5</span> Sky</a></li>
</ul>
</li>
</ul>
/** Color Bar **/
$("ul#color-hr > li > ul li a span").each(function (data, i) {
$this = $(this);
var colorArr = $this.map(function () { return $this.text() });
var barColor = 0;
for (var i = 0; i < colorArr.length; i++) {
console.log(colorArr);
$(this).css('backgroundColor', '#' + barColor);
}
});
答案 0 :(得分:3)
无需循环两次。
您可以将代码更改为:
$("ul#color-hr > li > ul li a span").each(function (data, i) {
$this = $(this);
$this.css('backgroundColor', '#' + $this.text());
});
答案 1 :(得分:3)
你不需要内循环。
$("ul#color-hr > li > ul li a span").each(function (data, i) {
$(this).css('backgroundColor', '#' + $(this).text())
});
另外,作为参考,您可能需要考虑HTML5“data-”属性。在这种情况下,这有点多余,但可以派上用场。
<li><a href="Javascript:"><span data-bg="#70859a">70859a</span> Jetstream</a></li>
......会使用:
$(this).css('backgroundColor', $(this).data("bg"))
答案 2 :(得分:2)
您不需要内循环,因为each
已遍历它们。
//for (var i = 0; i < colorArr.length; i++) {
//console.log(colorArr);
$(this).css('backgroundColor', '#' + $this.text());
//}
我没有使用等于0的barColor
,而是将其替换为当前迭代的文本。
JSfiddle:http://jsfiddle.net/L6Hfn/3/