开发者

What's the difference between these two selectors?

开发者 https://www.devze.com 2022-12-13 07:25 出处:网络
$(this).paren开发者_开发知识库ts(\'table:first > tbody > tr\') And $(this).parents(\'table:first\').children(\'tbody\').children(\'tr\')
$(this).paren开发者_开发知识库ts('table:first > tbody > tr')

And

$(this).parents('table:first').children('tbody').children('tr')


The difference is that the first selector is entirely within the parents call, whereas the second one isn't.

Therefore, the first one looks for all parents of this which match table:first > tbody > tr. (In other words, a tr containing this that is in the first table)

The second one will find the parent of this which matches table:first, then find all of the trs directly within tbodys of that parent. (In other words, all of the trs directly inside the parent table)


Maybe an example will help... start out with this HTML

<table border=1>
 <thead>
  <th>Outter Table</th>
 </thead>
 <tbody>
  <tr><td>1</td></tr>
  <tr>
   <td>
    <table border=1 width=100>
     <thead>
      <th>Inner Table</th>
     </thead>
     <tbody>
      <tr><td>2a</td></tr>
      <tr><td class="test">2b</td></tr>
      <tr><td>2c</td></tr>
     </tbody>
    </table>
   </td>
  </tr>
  <tr><td>3</td></tr>
 </tbody>
</table>

Apply this script:

$('.test').parents('table:first > tbody > tr').addClass('foo');
$('.test').parents('table:first').children('tbody').children('tr').addClass('bar');

Result:

<table border="1">
 <thead>
  <th>Outter Table</th>
 </thead>
 <tbody>
  <tr class="foo"><td>1</td></tr>
  <tr class="foo">
   <td>
    <table width="100" border="1">
     <thead>
      <th>Inner Table</th>
     </thead>
     <tbody>
      <tr class="bar"><td>2a</td></tr>
      <tr class="bar"><td class="test">2b</td></tr>
      <tr class="bar"><td>2c</td></tr>
     </tbody>
    </table>
   </td>
  </tr>
  <tr class="foo"><td>3</td></tr>
 </tbody>
</table>
0

精彩评论

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

关注公众号