我的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