【问题标题】:Jquery select html() or text() but not the nested span and divJquery 选择 html() 或 text() 但不是嵌套的 span 和 div
【发布时间】:2013-01-23 14:33:35
【问题描述】:

我需要从 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(只是脚本)。

【问题讨论】:

  • 跨度是否未闭合?
  • 您需要包裹在价格 div 中的运输信息吗?

标签: jquery jquery-selectors selector


【解决方案1】:
var price = $('.price').contents().filter(function() {
    return this.nodeType == 3;   //Filtering by text node
}).text();

demo

【讨论】:

    【解决方案2】:

    这应该可行:

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

    例子:

    '$54.99<div class="shipping-info">$5.99</div>'.replace(/(<([^>]+)>.*?<\/([^>]+)>)/ig, "");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多