我可以从一个类中获取InnerHTML值,并使用下面的代码输出到控制台
var price = document.getElementsByClassName("price1")[0].innerHTML;
console.log(price);但是,我现在想从3个类中获取数值,并将它们组合成一个数值。
HTML如下所示
<div class="price">
<span class="pounds">45</span>
<span class="seperator">.</span>
<span class="pence">99</span>
</div>所需的结果是将45.99作为数值输出到控制台。
发布于 2021-04-25 18:05:25
您可以保存所有值,并通过控制台记录这些值的插值。+的作用是将字符串转换为数字。
针对两个span元素嵌套的情况进行编辑:
const pounds = document.getElementsByClassName("pounds")[0].innerHTML;
const separator = document.getElementsByClassName("separator")[0].innerHTML.split('<')[0];
const pence = document.getElementsByClassName("pence")[0].innerHTML;
const price = +`${pounds}${separator}${pence}`
console.log(typeof price, price);<div class="price">
<span class="pounds">45</span>
<span class="separator">.<span class="pence">99</span></span>
</div>
发布于 2021-04-25 18:11:52
这里有一个很小的方法。
window.onload = function () {
const prices = document.getElementsByClassName("price");
Array.from(prices).forEach(function(oPrice){
let currentPrice = oPrice.querySelector(".pounds").innerHTML;
currentPrice += oPrice.querySelector(".seperator").innerHTML;
currentPrice += oPrice.querySelector(".pence").innerHTML;
console.log(currentPrice);
});
}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Prices</title>
</head>
<body>
<div class="price">
<span class="pounds">45</span>
<span class="seperator">.</span>
<span class="pence">99</span>
</div>
</body>
</html>
选择所有价格,然后通过querySelectors使用forEach“组装”价格。注意,"currentPrice“是一个字符串。如果需要将值转换为数字,则必须转换字符串。这对你有帮助吗?
https://stackoverflow.com/questions/67251990
复制相似问题