What's the difference between these two selectors?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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

And

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

回答1:

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)



回答2:

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>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!