我有一个包含各种动态生成的背景颜色的表格。我想使用 jQuery 用单元格的实际背景颜色填充表格单元格内容。我可以使用 $("td").text("newcontents");
更改单元格的内容。我尝试 $("td").text($(this).css("backgroundColor"));
将背景颜色放入单元格中,但背景颜色没有显示出来。
$("td").text(
$(this).css("backgroundColor")
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>
最佳答案
试试这个:
$("td").text(function() {
return $(this).css("backgroundColor");
});
.text方法可以将函数作为参数。在这种情况下,此函数必须返回值以用作集合中元素的新文本内容。
您的版本 $("td").text($(this).css("backgroundColor"));
不正确,因为在这种情况下 this
指向全局对象(即 window
对象),显然 $(this).css("backgroundColor")
什么也不返回。
$("td").text(function() {
return $(this).css("backgroundColor");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>lighten</td>
<td style="background-color: #d379a6;">10%</td>
<td style="background-color: white;">50%</td>
<td style="background-color: white;">100%</td>
</tr>
<tr>
<td>darken</td>
<td style="background-color: #ad3972;">10%</td>
<td style="background-color: #14060d;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
<tr>
<td>mix</td>
<td style="background-color: #b24a7e;">10%</td>
<td style="background-color: #632946;">50%</td>
<td style="background-color: black;">100%</td>
</tr>
</table>
关于javascript - 如何将内容设置为背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953758/