Javascript 在多个const语句中打印值
相关脚本:Javascript 在多个const语句中打印值,javascript,jquery,ajax,Javascript,Jquery,Ajax,相关脚本: window.onload = function calcPreco() { for(const cloud of Array.from(document.getElementsByName("cloud"))) { fetch("_config/buscar_valor.php?id="+cloud.getAttribute("cloudid")+"&periodicidade=monthly") .then(res => res.text())
window.onload = function calcPreco() {
for(const cloud of Array.from(document.getElementsByName("cloud"))) {
fetch("_config/buscar_valor.php?id="+cloud.getAttribute("cloudid")+"&periodicidade=monthly")
.then(res => res.text())
.then(preco => {
preco -= cloud.getAttribute("desconto");
const valor = cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
})
}
}
我需要用另一个类将它打印到另一个
,但在执行减法之前
我试过类似的方法,但没有成功:
.then(preco => {
const valor = cloud.querySelector(".NEW_CLASS").innerText = preco.toFixed(2).replace('.', ',');
preco -= cloud.getAttribute("desconto");
const valor = cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
})
也就是说,它必须首先打印原始值,然后打印完成减法运算的值
在这种情况下如何使用两个const语句?使用var或const时,请将其视为分配内存位置。当您在同一作用域中分配两个内存位置时,它将不知道该做什么。因此,请使用不同的名称或从变量声明中删除var/const。 一个好的做法是定义并使用:
var someVariable;
if(condition){
someVariable = 'some answer';
}
else
{
someVariable = "some other answer';
}
或连接:
var someVariable;
someVariable = "some"; // mostly this and the line above will be one line.
someVariable += " answer";
如果您这样做:
valor = "some html";
valor = "some other html"; // This will overwrite the first answer.
这也是一本好书:
可能是您正在寻找的:
var valor = cloud.querySelector(".NEW_CLASS").innerText = preco.toFixed(2).replace('.', ',');
preco -= cloud.getAttribute("desconto");
valor += cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
?? 没有任何内容引用该常量(
valor
)。但是,两次声明同一个变量(或常量)是没有意义的。看看你的代码,你根本不需要const
声明。@3iASD…他的建议几乎奏效了,分数有问题。在即将出现的第一个变量中:preco.toFixed(2).replace('.',',')
。如果我用逗号保留这个标点符号,它不会进行计算,也不会打印值。在这种情况下可以做什么?这不是在不同的货币之间转换吗。“,”的问题是它变成了一个文本值。一种解决方案是使用类似于data preco的属性,该属性是没有转换的数值。您可以对该值进行数学运算,然后使.innerText成为其中包含“,”转换的视觉效果。我只需删除到fixed(2)
,就可以修复它,我会有任何问题吗?可能。我用JavaScript运行了这个,这就是我得到的。1.20+2.23=3.429999999997解决固定问题的方法(2)是这样做:数学地板(preco*100)/100;