我正在编辑跨度中嵌套了另一个跨度的跨度值。我试图在我的.each()
函数中基本上排除嵌套跨度的类。
代码编辑了价格值购买从中减去一个百分比,问题是它还通过删除它来编辑货币代码范围。
$('.price').each(function() {
var val = $(this).text();
var num = parseFloat(val);
var discount = num - (num * .40);
$(this).text(discount);
});
HTML看起来像这样:
- <span class="price">1000 <span class="currency">KR</span></span><br>
- <span class="price">100 <span class="currency">KR</span></span><br>
- <span class="price">2000 <span class="currency">KR</span></span><br>
- <span class="price">6000 <span class="currency">KR</span></span><br>
- <span class="price">10000 <span class="currency">KR</span></span>
要排除嵌套div <span class="currency">KR</span>
,我运行以下内容:
$('.price').not('.currency').each(function() { //etc etc });
重要的是要注意逻辑必须是这样的,我只能使用嵌套的<span>
。
答案 0 :(得分:3)
使用.contents()
它将返回包括文本节点在内的所有节点,选择第一个节点并计算折扣,不选择第二个节点,预先设置折扣并将新字符串设置为html。
$(function() {
$('.price').each(function() {
var val = $(this).contents()[0].textContent;
var num = parseFloat(val);
var discount = num - (num * .40);
$(this).html(function(){
return $(this).html().replace(val, discount+" ");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">1000 <span class="currency">KR</span></span>
<br>
<span class="price">100 <span class="currency">KR</span></span>
<br>
<span class="price">2000 <span class="currency">KR</span></span>
<br>
<span class="price">6000 <span class="currency">KR</span></span>
<br>
<span class="price">10000 <span class="currency">KR</span></span>