JavaScript 拆分功能不起作用
JavaScript split function doesn't work
我有这个 JS 函数:
<p class="price text-center ng-binding" total-price="">€ 0.44</p>
<script>
function (){
var value = document.getElementByClassName("price text-center ng-binding").innerText;
var splited = value.split(" ");
var conversionValue = splited[1];
return conversionValue;
}
</script>
我想将“€ 0.44”分成两部分:“€”和“0.44”。
我做错了什么?
getElementByClassName()
isn't a function it should be getElementsByClassName()
note the s
at the end of element
.
您无法在 getElementsByClassName()
上调用 innerText
,因为函数 return 是一个元素数组,而是尝试 select 第一次出现,例如 :
document.getElementsByClassName("price text-center ng-binding")[0].innerText;
我建议在你的情况下使用 .querySelector()
因为它会直接定位元素,比如 :
document.querySelector('.price.text-center.ng-binding').innerText;
注意:你需要给你的函数起一个名字。
var value = document.querySelector('.price.text-center.ng-binding').innerText;
var splited = value.split(" ");
var conversionValue = splited[1];
console.log(conversionValue);
<p class="price text-center ng-binding" total-price="">
€ 0.44
</p>
我有这个 JS 函数:
<p class="price text-center ng-binding" total-price="">€ 0.44</p>
<script>
function (){
var value = document.getElementByClassName("price text-center ng-binding").innerText;
var splited = value.split(" ");
var conversionValue = splited[1];
return conversionValue;
}
</script>
我想将“€ 0.44”分成两部分:“€”和“0.44”。
我做错了什么?
getElementByClassName()
isn't a function it should begetElementsByClassName()
note thes
at the end ofelement
.
您无法在 getElementsByClassName()
上调用 innerText
,因为函数 return 是一个元素数组,而是尝试 select 第一次出现,例如 :
document.getElementsByClassName("price text-center ng-binding")[0].innerText;
我建议在你的情况下使用 .querySelector()
因为它会直接定位元素,比如 :
document.querySelector('.price.text-center.ng-binding').innerText;
注意:你需要给你的函数起一个名字。
var value = document.querySelector('.price.text-center.ng-binding').innerText;
var splited = value.split(" ");
var conversionValue = splited[1];
console.log(conversionValue);
<p class="price text-center ng-binding" total-price="">
€ 0.44
</p>