javascript - Print value in more than one const statement
问题描述
Related script:
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('.', ',');
})
}
}
I need it to print to another <span>
with another class, but before doing the subtraction.
I tried something like that, but it did not work:
.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('.', ',');
})
That is, it must first print the original value, and then the value with the subtraction done.
How to use two const statements in this case?
解决方案
使用 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('.', ',');
推荐阅读
- android - 在按钮上制作圆角的xml不起作用
- connection-string - 类库项目中连接字符串的appconfig文件?
- python - Python .replace() 函数可以替换整个短语吗?
- r - 将双引号添加到每行的第一个单词
- sql - 使用“IN”运算符时计算重复项
- firebase - Firebase 托管的 Flutter Web/Dart CORS 错误
- docker - 构建另一个镜像时如何使用现有 docker 镜像的层?
- validation - 输入文本字段的 Primefaces Wizard 验证问题
- javascript - Google 跟踪代码管理器事件未显示在 Universal Analytics 控制台中?
- python - Pyodbc 无法在 SQL Server 2008 中执行 proc