How to add a sequence of classes to three objects in one
I need to add:
- an ID to the table in my form
- a numbered sequence of classes to a certain amount of TD's in every next TR in that table (three td's in this case)
I've got next html开发者_StackOverflow-model:
<form id="myform">
<table>
<tr>
<td>some text</td>
<td>some text</td>
<td>some text</td>
</tr>
<tr>
<td>some text</td>
<td>some text</td>
<td>some text</td>
</tr>
</table>
</form>
I need that to be like this after jquery applied:
<form id="myform"> <!--no changes-->
<table id="table1"> <!--changed-->
<tr>
<td class="td1">some text</td> <!--changed-->
<td class="td2">some text</td> <!--changed-->
<td class="td3">some text</td> <!--changed-->
</tr>
<tr>
<td class="td1">some text</td> <!--changed-->
<td class="td2">some text</td> <!--changed-->
<td class="td3">some text</td> <!--changed-->
</tr>
</table>
</form>
Let's try:
$(function(){
$('#myform').find('table').each(function(i,e){
var $table = $(e);
$table.attr('id', 'table' + (parseInt($table.index(),10)+1));
$table.find('tr').each(function(i2,e2){
var $tr = $(e2);
$tr.find('td').each(function(i3, e3){
var $td = $(e3);
$td.addClass('td' + (parseInt($td.index(),10)+1));
});
});
});
});
Example: http://www.jsfiddle.net/YjC6y/43/
This should work pretty generic. Anyway I'm not sure if that is the best way to do it, but I'm sure the elegant & clever people at Stackoverflow will correct this if not.
$('#myform table').each(function(i, v) {
$(v).attr('id','table' + (i + 1)).find('tr').each(function(idx, val) {
$(val).children().each(function(index,element) {
$(element).addClass('td' + (index + 1));
});
});
});
Here the code you want to add in your script
$("#myform table").attr("id", "table1");
$("#myform table tr").each(function(){
$("td:eq(0)",$(this)).attr("id", "td1");
$("td:eq(1)",$(this)).attr("id", "td2");
$("td:eq(2)",$(this)).attr("id", "td3");
});
(function($) {
var id = 'myid';
var class_prefix = 'myclass-';
$("#myform").find('table')
.attr('id', id)
.find('tr').each(function(i,el) {
row = $(el);
row.children('td').each(function(k, col) {
$(col).addClass(class_prefix + k);
});
});
});
精彩评论