尝试将代码分解一下。 它失败了因为.css()
实际上是在父节点上调用的, this
是指你的上下文中的window
。
的jsfiddle
$(function(){
// Get all elements matching selector 'li span'
var spans = $("li span");
// Loop for each element in spans
spans.each(function () {
// Create the new element as a jQuery object
var elem = $('<div class="colorBox">test</div>');
// Set the new element's background-color to the attribute on the parent
// of the span
elem.css('background-color', $(this).parent().attr("data-background"));
// Prepend the new element to the span (insert it as the first child)
$(this).prepend(elem);
});
});
如果你的意思是在div
包含“Brick Red”,那么你需要使用.wrap()
或.wrapInner()
。
的jsfiddle
$(this).wrap(elem);
更新
如果您正在使用自定义复选框,我建议采用更加css驱动的方法,该方法利用<label>
标签。
的jsfiddle
HTML
<ul>
<li data-background="#C11B17">
<input type="checkbox" name="color[]" value="Brick_Red" id="checkbox1" />
<label for="checkbox1">
<span>Brick Red</span>
</label>
</li>
</ul>
CSS
input[type=checkbox] {
display:none;
}
input[type=checkbox] + label:before {
display:inline-block;
content:"";
width:1em;
height:1em;
background-color:#CCC;
}
input[type=checkbox]:checked + label:before {
background-color:#C11B17;
}
请注意,此方法可在IE8 +中使用,无需任何polyfill。