【问题标题】:Using jQuery, how do you select an element that is a child of $(this)?使用 jQuery,你如何选择 $(this) 的子元素?
【发布时间】:2013-09-08 08:15:06
【问题描述】:

粗略的 HTML 结构:

<div class="wrapper">
  <p></p>
  <p></p>
  <p></p>
</div>
<div class="wrapper">
  <p></p>
  <p></p>
  <p></p>
</div>
<div class="wrapper">
  <p></p>
  <p></p>
  <p></p>
</div>

假设我有这样的功能:

$('div.wrapper').each(function() {
    // more stuff
});

我基本上想做这样的事情:

$(this).('p:eq(2)').remove();

$(this).('p:contains("old text")').text('new text');

$(this)开头我只想选择其中的子元素。

【问题讨论】:

  • $('p', this)一样使用它作为上下文,或者像$(this).find('p')一样使用find()

标签: jquery dom jquery-selectors this


【解决方案1】:

你可以这样做:

$('div.wrapper').each(function() {
    $('p:eq(2)', this).remove();
});

它使用this 作为与您要查找的元素相关的容器或父级。

$('div.wrapper').each(function() {
    $(this).find('p').eq(2).remove();
});

它使用.find() 来做和上面一样的事情。

jsFiddle example

【讨论】:

  • 这似乎正是我想要的。谢谢!正如您在第一个示例中演示的那样,我还不明白您可以使用上下文。使用相同的第一个示例,您建议最简单的方法是在第一个之后包含仅针对包装器 DIV 的方法,但不包括第一个?我尝试了:gt(0).slice(),但没有成功。
  • 如果您想对 div 做某事但不是第一个,您可以在末尾添加 .not(':first')。像这样jsfiddle.net/j08691/tvJ6e/1
  • 道歉。我的意思是忽略第一个 div,然后只查找第二个及以后的项目。
  • 啊,这同样简单。使用$('div.wrapper').not(':first')$('div.wrapper:gt(0)') 而不是$('div.wrapper')
【解决方案2】:
$('.wrapper p').eq(1).remove();   

.find() 是您可以查找的另一种方法。

【讨论】:

    【解决方案3】:

    只获取$(this) 的孩子,您可以使用:

    $(this).children();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2015-12-06
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多