像一些现有示例一样,我只想在选择器中选择TD的第一级,这里的区别在于操作是在现有选择上进行的。
假设我有一个像这样的桌子...
<table border=1>
<tr trid="1">
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
<tr trid="2">
<td>cell 1</td>
<td>
<table border=1>
<tr>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
<tr>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</table>
</td>
<td>cell 3</td>
</tr>
<tr trid="3">
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</table>
我想最初逐行遍历此特定表。我只想遍历具有“ trid”的自定义属性的行。
我设法做到了...
$('tr[trid]').each(function(index)
{
//gets properties of TR here
$('td',this).each(function(index)
{
$(this).css('background-color', 'red'); //turn my cells red
});
});
现在可以使用,但是我只想要第一级单元。因此,我希望TD循环忽略第二级的td。
我知道外部循环是否使用tr [trid]> td可以正常工作,但是我随后跳过了循环的重要部分。我是否可以使用语法在现有选择项上进行此类操作,即确保所选td的父项具有tr [tabid]。
这一点非常特别,因为我无论如何都无法添加新样式或更改现有的HTML。同样,JQuery循环的顺序也很重要,因为它在运行时会输出并需要保留其顺序。
谢谢 :)
最佳答案
代替
$('td',this).each(function(index)
采用
$(this).children('td').each(function(index)
例如:http://jsfiddle.net/gaby/tz2jt/1/
或更神秘的(但你明白了)
$('> td',this).each(function(index)
例如:http://jsfiddle.net/gaby/tz2jt/