简体   繁体   English

jQuery Selector-孩子的孩子

[英]jQuery Selector - Children of children

I have the following jquery snippets (used with each to iterate over a table of results): 我有以下jquery片段(与each片段一起用于遍历结果表):

$('.foo').children('.bar').children('.first_baz').text();
$('.foo').children('.bar').children('.second_baz').text();

I use this to access $firstvalue and $secondvalue : 我用它来访问$firstvalue$secondvalue

<tr class='foo'>
<td class='bar'><span class='first_baz'>".$firstvalue."</span><span class='second_baz'>".$secondvalue."</span></td>
</tr>

This works but is it efficient? 这有效,但是有效吗? I suspect there is a better way to access these values... what is it? 我怀疑有更好的方法来访问这些值...这是什么?

If the first_baz and second_baz elements are just with in the table and no where else in the page then you can skip the children function use the following snippet: 如果first_baz和second_baz元素仅在表格中,而在页面中的其他地方不存在,则可以使用以下代码段跳过子功能:

$('.first_baz').text(); 
$('.second_baz').text(); 

If the above case doesn't hold good then you can shorten the statements to 如果上述情况不好,则可以将语句缩短为

var parent = $('.foo'); //Get the parent context so that its not queried twice
$('.first_baz', parent).text(); 
$('.second_baz', parent).text(); 

You could cache all the .bar . 您可以缓存所有.bar

var bar = $('.foo').children('.bar')
bar.children('.first_baz').text();
bar.children('.second_baz').text();

I haven't tried but this should be more efficient. 我没有尝试过,但这应该更有效。

$('.foo .bar .first_baz').text();
$('.foo .bar .second_baz').text();
$('span.first_baz').text() 

if you don't need the parent structure, or 如果您不需要父结构,或者

$('tr.foo > td.bar > span.first_baz').text()

if you do. 如果你这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM