Add array values as table rows classes
I need to go through array and add it's values as table rows classes where table cells has "colspan=10".
Here is my html:
<tbody>
<tr>
<td><a href="#"><img src=""></a></td>
<td width="100%" align="left" colspan="10"><a href="#">Anchor</a></td>
</tr>
&l开发者_如何转开发t;tr>
<td colspan="1" class="text"><img></td>
<td valign="top" nowrap="" align="right"><a href="#"><img src=""></a></td>
<td width="100%" align="left" colspan="9" class="smalltext"><a href="#" class="dottedlink">Anchor</a></td>
</tr>
<tr>
<td colspan="1" class="text"><img></td>
<td valign="top" nowrap="" align="right"><a href="#"><img src=""></a></td>
<td width="100%" align="left" colspan="9" class="smalltext"><a href="#" class="dottedlink">Anchor</a></td>
</tr>
<tr>
<td><a href="#"><img src=""></a></td>
<td width="100%" align="left" colspan="10"><a href="#">Anchor</a></td>
</tr>
</tbody>
Please help! I'm totally new in jquery
PS I can add the same class but not from array
This should do what you are asking for
var classes = ['one', 'two', 'three', 'whatever']; // <-- your class array
var $cells = $('td[colspan=10]'); // <-- selects table cells with colspan=10
$cells.each(function(index, element){ // <-- executes this function for each cell in the $cells list
var row = $(element).parent('tr'); // navigate to parent element <tr>
row.addClass( classes.shift() ); // <-- shift() removes and returns first element in the list
// ^-- addClass adds the string as a class without removing previous classes
});
Of course that is for educational purposes. In real life you would write the same code more concisely:
var classes = ['one', 'two', 'three', 'whatever'];
$('td[colspan=10]').each(function(index, element){
$(element).parent('tr').addClass(classes.shift());
});
So you have an array like this:
var array = [];
array.push('classA');
array.push('classB');
Now you want to addo both classes to <td>
with colspan = 10.
You can do: (EDIT - i added what suggested in the comment)
$('td[colspan=10]').each(function(){
$(this).addClass(array.join(' '))
}
I do not understand clearly what you are trying to achive, but you can get array of your td
elements with colspan equals to 10 by using query: $("td[colspan=10]")
, then you can add class to each of them and it can finally look like: $("td[colspan=10]").addClass("myclass")
. If you will go further you can add those classes not to td
but to parent tr
elements:
$("td[colspan=10]").each(index, el) {
el.parents("tr").addClass("myclass");
}
Please let me know if it is what you wanted to achive...
精彩评论