我的HTML的其餘部分如下:獲得來自標籤的文本,而不內容
<span class="price">
0
<sup>$</sup>
</span>
我怎樣才能得到只有0
沒有<sup>$</sup>
。
我想:
var total = parseFloat($('.price').text());
感謝。
我的HTML的其餘部分如下:獲得來自標籤的文本,而不內容
<span class="price">
0
<sup>$</sup>
</span>
我怎樣才能得到只有0
沒有<sup>$</sup>
。
我想:
var total = parseFloat($('.price').text());
感謝。
$( 「價格」)
返回一個集合或數組,你需要指定的元素。在這種情況下,您可以使用JQuery eq函數指定它。
var total = parseFloat($('.price').eq(0).text());
我使用0(零),因爲你的HTML只與類價格一個元素
試試看youself: https://jsfiddle.net/ggderas/Ln7gd74n/3
試試這個
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>
我認爲這是一段美麗的代碼,但僅僅刪除我需要的內容太難了。 – Bonito
謝謝你說它是一段美麗的代碼 – EaBangalore
獲取innerHTML
和刪除任何東西里面標籤:
var text = document.getElementsByClassName('price')[0].innerHTML.replace(/<.*>.*<\/.*?>/g, '');
console.log(text);
<body>
<span class="price">
0
<sup>$</sup>
</span>
<?body>
假設有一類的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);
,你可以很容易地通過分裂像下面
<!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>
'的.text()'獲取文本時不包含HTML標籤,這樣你就不會得到'':https://jsfiddle.net/6m48w40s/ –
@JonP:你讀快速我的文字,我認爲。 – Bonito