【问题标题】:How to Set a Different Image for Each Row in a jQuery Table using CSS如何使用 CSS 为 jQuery 表中的每一行设置不同的图像
【发布时间】:2019-12-23 05:05:11
【问题描述】:

我有一个使用 jQuery 创建表的外部文件。 我已经想出了如何将背景图像设置为 css 中的 td 属性,但是由于表格有 4 行,因此每行中的每个单元格都获得相同的图像。 我希望每一行都有不同的图像(但在行中的每个单元格中都是相同的)。 最终,我希望每个图像都可以点击并运行一个将变量传递给该函数的函数,但我仍在努力解决这个问题(到目前为止收效甚微)。

这是桌子:

var $table = $('<table>');
$table.append()

//tbody
var $tbody = $table.append('<tbody />').children('tbody');

// add row
$tbody.append('<tr />').children('tr:last')
.append("<th>Clear</th>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>");

// add another row
$tbody.append('<tr />').children('tr:last')
.append("<th>Earlies</th>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>");

// add another row
$tbody.append('<tr />').children('tr:last')
.append("<th>Lates</th>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>");

// add another row
$tbody.append('<tr />').children('tr:last')
.append("<th>Double</th>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>")
.append("<td></td>");

// add table to dom
$table.appendTo('#dynamicTable');

});

这是css:

#dynamicTable td {
    background-image: url(../images/clear_32px.gif); 
}

【问题讨论】:

  • 我想我需要以某种方式使用类?尤其是当我打算为单行中的每个 td 使用相同的 id 时。我只是读到不要使用它,而是使用类(我想我读对了)。

标签: jquery css image html-table


【解决方案1】:

您可以使用 css 伪 nth-child https://developer.mozilla.org/de/docs/Web/CSS/:nth-child

例如:

#dynamicTable tr:nth-child(1) td {
    background-image: url(../image1.gif); 
}
#dynamicTable tr:nth-child(2) td {
    background-image: url(../image2.gif); 
}
#dynamicTable tr:nth-child(3) td {
    background-image: url(../image3.gif); 
}
#dynamicTable tr:nth-child(4) td {
    background-image: url(../image4.gif); 
}

【讨论】:

  • 非常感谢。效果很好。
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2015-08-21
  • 2012-05-15
  • 1970-01-01
  • 2015-08-04
相关资源
最近更新 更多