相关脚本:

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

最佳答案

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

关于javascript - 在多个const语句中打印值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52066891/

10-12 12:30
查看更多