user11853168
user11853168

Reputation:

How to Set a Different Image for Each Row in a jQuery Table using CSS

I have an external file that creates a table using jQuery. I have figured out how to set a background image to the td attribute in css but as the table has 4 rows, each cell, in each row, gets the same image. I would like each row to have a different image (but identical in each cell in the row). Eventually I want each image to be clickable and run a function that passes a variable to that function but I am still working on this (with little success so far).

This is the table:

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');

});

This is the css:

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

Upvotes: 1

Views: 23

Answers (1)

tom
tom

Reputation: 10601

You could use the css pseudo nth-child https://developer.mozilla.org/de/docs/Web/CSS/:nth-child

E.G.:

#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); 
}

Upvotes: 1

Related Questions