结合使用insertAfter()和'this'

时间:2019-04-04 15:04:53

标签: jquery dom this

我有_transferWindowOwnership个产品的n个divs。对于每个.paymentContainer,我都想节省下来,放在n和类.paymentContainer的div之间,但是我的jQuery语句仍然出错。关于为什么我的jQuery无法正常工作的任何想法?

<price>
button

1 个答案:

答案 0 :(得分:1)

这里有两个问题。首先,HTML没有<price>元素。我建议改为将spanprice类一起使用。

第二,div中不能包含p元素,因为它是无效的HTML。

最后,在这种情况下,您需要使用find()来选择要定位的元素,因为它们是.paymentContainer的子孙,而children()只是在子级。试试这个:

$('div.paymentContainer').each(function() {
  $(this).children('p.savings').insertAfter($(this).find('p.pricing > .price'))
});
.paymentContainer {
  border: 1px solid #CCC;
}
.savings {
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="paymentContainer">
  <div>some content</div>
  <p class="pricing">
    <span class="price">$xxx.xx</span>
    <span class="button">add to cart</span>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>
<div class="paymentContainer">
  <div>some content</div>
  <p class="pricing">
    <span class="price">$xxx.xx</span>
    <span class="button">add to cart</span>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>
<div class="paymentContainer">
  <div>some content</div>
  <p class="pricing">
    <span class="price">$xxx.xx</span>
    <span class="button">add to cart</span>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>

话虽如此,使用Java脚本对这样的元素重新排序并不理想。如果可能的话,最好直接修改HTML源代码。