【问题标题】:What's the difference between these two selectors?这两个选择器有什么区别?
【发布时间】:2010-12-24 06:27:17
【问题描述】:
$(this).parents('table:first > tbody > tr')

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

【问题讨论】:

  • 使用最接近的而不是父母 & :first
  • @redsquare:我们不知道他到底想选择什么。
  • 最近的 == parents('table:first')
  • 所以我是说你应该总是使用最接近父母和 :first....不管他试图选择什么
  • 为什么不去看看文档来揭示所有内容......docs.jquery.com/Traversing/closest

标签: jquery


【解决方案1】:

不同之处在于第一个选择器完全在 parents 调用中,而第二个不是。

因此,第一个查找与table:first > tbody > tr 匹配的this 的所有父母。 (换句话说,包含thistr 位于第一个table 中)

第二个将查找与table:first 匹配的this 的父级,然后直接在该父级的tbodys 中查找所有trs。 (也就是说,所有的trs都直接在父表里面)

【讨论】:

  • 似乎反直觉。我读第一个和第二个完全一样。当然懒得去测试了。
  • @ChaosPandion:请仔细阅读。你会明白我的意思。
  • 根据您的解释,我仍然看不出有什么不同,尽管我自己已经介入了这个问题..
  • 仔细阅读。另外,查看第二行创建的中间对象中匹配的元素($(this).parents('table:first')$(this).parents('table:first').children('tbody')
  • 难道“> tr”也表示“直接在里面”吗?
【解决方案2】:

也许一个例子会有所帮助...从这个 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>

应用此脚本:

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

结果:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 2012-06-12
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多