首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对'this‘使用insertAfter()

对'this‘使用insertAfter()
EN

Stack Overflow用户
提问于 2019-04-04 23:04:53
回答 1查看 56关注 0票数 0

我有一些n产品的n .paymentContainer div。对于每个.paymentContainer,我想把节省下来的钱放在<price>button类的div之间,但是我的jQuery语句仍然出错。关于我的jQuery为什么不能工作有什么想法吗?

代码语言:javascript
复制
$('div.paymentContainer').each(function() {
  $(this).children('p.savings').insertAfter($(this).children('p.pricing > price'))
});
代码语言:javascript
复制
<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">
    <price>$xxx.xx</price>
    <div class="button">add to cart</div>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>
<div class="paymentContainer">
  <div>some content</div>
  <p class="pricing">
    <price>$xxx.xx</price>
    <div class="button">add to cart</div>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>
<div class="paymentContainer">
  <div>some content</div>
  <p class="pricing">
    <price>$xxx.xx</price>
    <div class="button">add to cart</div>
  </p>
  <p class="savings">Save $yy.yy</p>
</div>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-04 23:13:59

这里有几个问题。首先,超文本标记语言没有<price>元素。我建议使用带有price类的span

其次,不能在p中包含div元素,因为它是无效的超文本标记语言。

最后,在本例中,您需要使用find()来选择您试图定位的元素,因为它们是.paymentContainer的孙子元素,而children()只查看子级。试试这个:

代码语言:javascript
复制
$('div.paymentContainer').each(function() {
  $(this).children('p.savings').insertAfter($(this).find('p.pricing > .price'))
});
代码语言:javascript
复制
.paymentContainer {
  border: 1px solid #CCC;
}
.savings {
  color: #C00;
}
代码语言:javascript
复制
<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>

尽管如此,使用Javascript来重新排序像这样的元素并不理想。如果可能的话,直接修改HTML源代码会更好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55519282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档