javascript - 如何将内容设置为背景颜色?

标签 javascript jquery css

我有一个包含各种动态生成的背景颜色的表格。我想使用 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/

相关文章:

javascript - 延迟加载不会加载可见图像

css - durandal.js - 是否可以通过 View 按需加载 View 特定的 css?

javascript - 为什么 React Router 会导致 Web 应用程序崩溃?

javascript - Access-Control-Allow-Origin 不从 PHP 发送

javascript - 为什么我不能总结数组的所有属性?

html - 没有固定高度的单行和多行CSS的垂直居中

html - 如何为与文本相关的 Angular Material 的 mdRadioButton 指令设置垂直对齐?

javascript - sidr 菜单关闭在 Chrome 移动设备中不起作用

javascript - Handlebars 显示 html 标签而不是将其视为 html 标签

javascript - 无法从 Sublime Text 中的 html 访问 javascript 代码