Reputation: 12836
How could I write javascript that iterates through a table, grabs the class, and then replaces with an image? So for example I have a table with columns that have numeric classes appended to them:
<td class="images 12-345"></td>
<td class="images 98-763"></td>
These numbers coorelate with image names that I want to load with javascript after the rest of the query is finished processing. So the final product would look like :
<td class="images 12-345"><img src="http://site.com/12-345.jpg"></td>
<td class="images 98-763"><img src="http://site.com/98-763.jpg"></td>
But not until everything is done loading. I would like to just have a placeholder graphic in there that is replaced with the correct image file after everything has processed.
How would I iterate through these rows and then load the appropriate image to each cell? I was thinking first I could use the .images selector to retrieve each unique numeric class name and pass that into a variable. Then with that variable I could append it to the rest of the image path and place it back into its appropriate table cell. I would not want this to begin processing until the rest of the dom had finished loading and the original sql query had completed. Can I please have some advice on what would be the best way to write this. jQuery is an option for me.
Upvotes: 0
Views: 55
Reputation: 434635
You could do something like this with jQuery:
$('td.images').each(function() {
var $td = $(this);
var classes = $(this).attr('class').split(/\s+/);
var num = $.grep(classes, function(c) { return c.match(/^[\d-]+$/) });
if(num.length)
$td.append('<img src="http://site.com/' + num[0] + '.jpg">');
});
Demo (with just the numbers in the cells): http://jsfiddle.net/ambiguous/vrDvc/1/
You might need to adjust the $.grep
and how you handle the num
array to match your real data but the basic technique should work.
Upvotes: 1