在多个const语句中打印值

时间:2018-08-28 22:13:59

标签: 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())
     .then(preco => {
        preco -= cloud.getAttribute("desconto");
        const valor = cloud.querySelector(".mostrar_valor").innerText = preco.toFixed(2).replace('.', ',');
     })
    }
}

我需要将它打印到另一个类的另一个<span>上,但是要先减去。

我尝试了类似的方法,但是没有用:

.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语句?

1 个答案:

答案 0 :(得分:1)

使用var或const时,请将其视为分配内存位置。当您在同一范围内分配2个内存位置时,它将不知道该怎么办。因此,请使用其他名称或从变量声明中删除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.

也很好读:

https://airbrake.io/blog/javascript-error-handling/redeclaration-formal-parameter-x

可能是您要找的东西:

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('.', ',');