2

我需要从 div 中选择价格,但问题是有时元素内还有一个额外的嵌套 div 和/或 span。

我想知道是否有办法使用 :not 选择器,或者我是否必须获取 html 的值并清除有时存在的 span 和 div 。

$('.price').text();//returns the additional text from the span and div
$('.price').html();//returns the span and div tags and text

<!-- Simplified html -->
<div class="product">
<div class="price">$19.95
</div>
</div>

<!-- This product has shipping info inserted -->
<div class="product">
<div class="price"> $54.99
<div class="shipping-info">$5.99</div>
</div>
</div>

<!-- This product has the original price in a span and the shipping info inserted -->
<div class="product">
<div class="price"><span>$189.99</span>$99.99
<div class="shipping-info">Free Shipping</div>
</div>
</div>

我需要获取价格的价值(19.99 美元、54.99 美元、99.99 美元),而不是额外的跨度或运输信息。

我无法更改 HTML(只是脚本)。

4

2 回答 2

3
var price = $('.price').contents().filter(function() {
    return this.nodeType == 3;   //Filtering by text node
}).text();

演示

于 2013-01-23T14:47:15.983 回答
0

这应该有效:

price.replace(/(<([^>]+)>.*?<\/([^>]+)>)/ig, "");

例子:

'$54.99<div class="shipping-info">$5.99</div>'.replace(/(<([^>]+)>.*?<\/([^>]+)>)/ig, "");
于 2013-01-23T14:39:25.617 回答