2016-11-17 30 views
1

我的HTML的其余部分如下:获得来自标签的文本,而不内容

<span class="price"> 
    0 
    <sup>$</sup> 
</span> 

我怎样才能得到只有0没有<sup>$</sup>

我想:

var total = parseFloat($('.price').text()); 

感谢。

+0

'的.text()'获取文本时不包含HTML标签,这样你就不会得到'':https://jsfiddle.net/6m48w40s/ –

+0

@JonP:你读快速我的文字,我认为。 – Bonito

回答

1

$( “价格”)

返回一个集合或数组,你需要指定的元素。在这种情况下,您可以使用JQuery eq函数指定它。

var total = parseFloat($('.price').eq(0).text()); 

我使用0(零),因为你的HTML只与类价格一个元素

试试看youself: https://jsfiddle.net/ggderas/Ln7gd74n/3

+0

我认为您的解决方案可能是最好的一个。 – Bonito

+0

除了这仍然返回0为$'$ EQ(0)的.text()'( '价格')。https://jsfiddle.net/ab5ne0rh/ –

+0

随意给它一个镜头:https://开头的jsfiddle。net/ggderas/Ln7gd74n/ – ggderas

1

试试这个

var price = $('.price').contents().map(function() { 
 
       if (this.nodeType == 3 && this.textContent.trim() != '') return Number(this.textContent); 
 
     }).get().join(); 
 

 
console.log(price);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span>

+0

我认为这是一段美丽的代码,但仅仅删除我需要的内容太难了。 – Bonito

+0

谢谢你说它是一段美丽的代码 – EaBangalore

0

获取innerHTML和删除任何东西里面标签:

var text = document.getElementsByClassName('price')[0].innerHTML.replace(/<.*>.*<\/.*?>/g, ''); 
 
console.log(text);
<body> 
 
    <span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span> 
 
    <?body>

0

假设有一类的price只有一个对象,并要忽略在孩子的任何文本节点...

var total = parseFloat($('.price')[0].childNodes[0].nodeValue); 
 
console.log(total); 
 
console.log($('.price')[0].childNodes[0].nodeValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<span class="price"> 
 
    0<sup>$</sup> 
 
</span>

这也适用于没有jQuery的有轻微的修改:

var total = parseFloat(document.getElementsByClassName('price')[0].childNodes[0].nodeValue); 
1

,你可以很容易地通过分裂像下面

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
</head> 
 
<body> 
 

 
<span class="price"> 
 
    0 
 
    <sup>$</sup> 
 
</span> 
 

 

 
</body> 
 

 

 
<script type="text/javascript"> 
 
\t $(document).ready(function(){ 
 
\t \t var thePricewith_$ = $(".price").text(); // get the text 
 
\t \t var splitted = thePricewith_$.split("$"); // split it from dollar sign 
 

 
\t \t var onlyPrice = splitted[0]; // this gives the price text 
 
\t \t var dollarSign = splitted[1]; // this gives the dollar sign 
 
\t \t alert("price without dollar sign : "+ onlyPrice) // print only the price 
 

 
//additional, if you want to convert it to int and use it do it like this 
 
// var piceInt = parseInt(onlyPrice) 
 
// alert(piceInt+5) 
 

 

 
\t }); 
 

 
</script> 
 

 

 
</html>

  • 得到它,你也拐杖将其转换int和注释中使用它。希望这会对你有所帮助。
相关问题