开发者

jQuery Selector - Children of children

开发者 https://www.devze.com 2023-02-22 08:52 出处:网络
I have the following jquery snippets (used with each to iterate over a table of results): $(\'.foo\').children(\'.bar\').children(\'.first_baz\').text();

I have the following jquery snippets (used with each to iterate over a table of results):

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

I use this to access $firstvalue and $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').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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消