使用jQuery,如何选择$(this)子元素?

时间:2013-09-04 17:34:54

标签: jquery dom jquery-selectors this

粗糙的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)开始,我只想在其中选择子元素。

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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

使用this作为相对于您要查找的元素的容器或父级。

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

使用.find()执行与上述相同的操作。

<强> jsFiddle example

答案 1 :(得分:0)

$('.wrapper p').eq(1).remove();   

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

答案 2 :(得分:0)

只能使用$(this)的孩子:

$(this).children();