我有下面的html:
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Batman Graphic Tee - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $14.99</p>
<p class="pt_5 oos">Superman Flying Graphic Tee</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Spiderman vs Venom Hoodie - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $9.99</p>
<p class="pt_5 oos">Wolverine vs Magento Tank</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Hulk vs Thanos - Out Of Stock</p>
</div>
如果满足某个条件,我将使用下面的函数用类'oos_msg‘更新'P’标记中的文本。
$('.oos').text(function() {
if ($('.oos:contains("Out Of Stock")')) {
$('.oos_msg').html('Out Of Stock');
}
})
我遇到的问题是,它正在更新每个'P‘标记,它有一个类oos_msg,我做错了什么?
JSFiddle链接:https://jsfiddle.net/jingz/3r5L84e6/17/
发布于 2018-08-02 06:43:09
有两个问题:
$('.oos_msg')
选择器将选择所有.oos_msg
元素,因此所有这些元素的.html()
都将更新。要纠正这一点,可以结合使用和 来处理所包含的文本,使用来仅针对正在循环的当前元素。
这可以从以下几个方面看出来:
$('.oos').text(function() {
if ($(this).is(':contains("Out Of Stock")'))
$(this).prev().html('Out Of Stock');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Batman Graphic Tee - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Superman Flying Graphic Tee</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Spiderman vs Venom Hoodie - Out Of Stock</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Wolverine vs Magento Tank</p>
</div>
<div class="t_gray t_small mb_10">
<p class="t_bold pt_5 oos_msg">CAD $0.00</p>
<p class="pt_5 oos">Hulk vs Thanos - Out Of Stock</p>
</div>
https://stackoverflow.com/questions/51643137
复制相似问题