请你看一下这个演示,让我知道为什么我不能根据它的数据属性为每个元素应用背景颜色?
$(".btn-color").each(function(){
$(this).css("background-color", $(this).data('bg'));
});
$(".btn-color").css("background-color", $(this).data('bg'));
.btn-color{
height:40px;
width:40px;
border-radius:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-1"><button class="btn btn-color" data-bg="D8BFD8"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FF6347"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="40E0D0"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="EE82EE"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="F5DEB3"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FFFFFF"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="F5F5F5"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FFFF00"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="9ACD32"></button></div>
</div>
答案 0 :(得分:5)
你没有十六进制颜色,你只需要一个随机字符串。您需要输入井号#
才能使颜色生效。
$(".btn-color").each(function(){
$(this).css("background-color", "#" + $(this).data('bg'));
});
&#13;
.btn-color{
height:40px;
width:40px;
border-radius:50%;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-1"><button class="btn btn-color" data-bg="D8BFD8"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FF6347"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="40E0D0"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="EE82EE"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="F5DEB3"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FFFFFF"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="F5F5F5"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="FFFF00"></button></div>
<div class="col-sm-1"><button class="btn btn-color" data-bg="9ACD32"></button></div>
</div>
&#13;