2016-11-17 31 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和註釋中使用它。希望這會對你有所幫助。
相關問題