jquery获取现有选择中的第一级td元素
与一些现有示例一样,我只想选择选择器中 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 循环的顺序也很重要,因为它在运行时输出并且需要保留其顺序。
谢谢 :)
Like some existing examples I want to select only the first level of TD's within a selector, the difference here is that the operation is on an existing selection.
Let's say I have a table like so...
<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>
I want to initially traverse this particular table row by row. I only want to traverse the rows that have a custom attribute of "trid".
I managed to get this far...
$('tr[trid]').each(function(index)
{
//gets properties of TR here
$('td',this).each(function(index)
{
$(this).css('background-color', 'red'); //turn my cells red
});
});
Now this works but I only want the first level of Cells. So I want the TD loop to ignore the second level of td's.
I know if the outer loop used tr[trid]>td this would work however I then skip an important part of the loop. Is there syntax I can use to operate like this on the existing selection, i.e. ensuring the parent of the selected td has the tr[tabid].
This is quite particular in that I cannot add new styles or change the existing HTML in anyway. Also the order of the JQuery loop is also important since it outputs as it runs and needs to retain it's sequence.
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
而不是
使用
示例: http://jsfiddle.net/gaby/tz2jt/1/
或更神秘的(但你明白了)
示例: http://jsfiddle.net /加比/tz2jt/
Instead of
use
example: http://jsfiddle.net/gaby/tz2jt/1/
or the more cryptic (but you get the idea)
example: http://jsfiddle.net/gaby/tz2jt/
您可以使用
.children()
方法来遍历您调用它的元素的直接子元素。You can use the
.children()
method which traverses the immediate children of the elements you're calling it on.