jQuery:在一个范围内包含div中的数字

时间:2015-04-10 15:38:11

标签: javascript jquery html css

我正在试图弄清楚这是否可能,我有一个类似下面标记的设置:

<div class="price-wrap">£12.95</div>
<div class="price-wrap">from £9.95</div>
<div class="price-wrap">£6.95</div>
<div class="price-wrap">£16.95</div>
<div class="price-wrap">£11.95</div>
<div class="price-wrap">from £1.95</div>

但我最理想的是,如果可能的话,就是这样:

<div class="price-wrap">£<span class="price">12.95</span></div>
<div class="price-wrap">from £<span class="price">9.95</span></div>
<div class="price-wrap">£<span class="price">6.95</span></div>
<div class="price-wrap">£<span class="price">16.95</span></div>
<div class="price-wrap">£<span class="price">11.95</span></div>
<div class="price-wrap">from £<span class="price">1.95</span></div>

因此,只需将数字包含在span标记中,其中price类不包括任何£from等等。 任何建议将不胜感激!

3 个答案:

答案 0 :(得分:3)

这应该做:

$('.price-wrap').each(function() {
    var $this = $(this);
    $this.html($this.html().replace(/([0-9.]+)/g, '<span>$1</span>'));
});

答案 1 :(得分:2)

您可以使用.html()中的回调迭代每个div的内容:

$('div.price-wrap').html(function () {
    var val = $(this).text().split('£');
    return val[0] + '£<span class="price">' + val[1] + '</span>'
})
.price {
    color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price-wrap">£12.95</div>
<div class="price-wrap">from £9.95</div>
<div class="price-wrap">£6.95</div>
<div class="price-wrap">£16.95</div>
<div class="price-wrap">£11.95</div>
<div class="price-wrap">from £1.95</div>

答案 2 :(得分:0)

也许你可以使用正则表达式并用<span>float</span>

替换浮点数

正则表达式匹配浮动([-+]?[0-9]*\.?[0-9]+)