gpt4 book ai didi

javascript - 在文本大于的 span 之后添加 HTML

转载 作者:行者123 更新时间:2023-11-28 14:21:18 25 4
gpt4 key购买 nike

我有部分 HTML:

<div class="product">
<h1>Product 1</h1>
<img src="">
<span class="price">435</span>
</div>
<div class="product">
<h1>Product 2</h1>
<img src="">
<span class="price">599</span>
</div>
<div class="product">
<h1>Product 3</h1>
<img src="">
<span class="price">850</span>
</div>
<div class="product">
<h1>Product 4</h1>
<img src="">
<span class="price">239</span>
</div>

我要添加<p>Free shipping</p>之后<span class="price">价格大于400的产品。

最佳答案

您可以使用 jQuery 的 .each()after()

$('.price').each(function(){
if($(this).text() > 400)
$(this).after('<p>Free shipping</p>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product">
<h1>Product 1</h1>
<img src="">
<span class="price">435</span>
</div>
<div class="product">
<h1>Product 2</h1>
<img src="">
<span class="price">599</span>
</div>
<div class="product">
<h1>Product 3</h1>
<img src="">
<span class="price">850</span>
</div>
<div class="product">
<h1>Product 4</h1>
<img src="">
<span class="price">239</span>
</div>

您也可以在普通 JS 中实现这一点

var allPrice = [].slice.call(document.querySelectorAll('.price'));
allPrice.forEach(function(el){
if(el.textContent > 400){
var p = document.createElement('p');
p.textContent = 'Free shipping';
el.parentNode.insertBefore(p, el.nextSibling);
}
});
<div class="product">
<h1>Product 1</h1>
<img src="">
<span class="price">435</span>
</div>
<div class="product">
<h1>Product 2</h1>
<img src="">
<span class="price">599</span>
</div>
<div class="product">
<h1>Product 3</h1>
<img src="">
<span class="price">850</span>
</div>
<div class="product">
<h1>Product 4</h1>
<img src="">
<span class="price">239</span>
</div>

关于javascript - 在文本大于的 span 之后添加 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com