javascript - Javascript/HTML 在浏览器上的值更改之前显示警报
问题描述
我有一个简单的计数器网页,它有一个“+1”按钮和一个计数显示。当您点击按钮时,网页上的计数会增加 1。当计数达到 5 时,页面应该会弹出警报并将计数器重置为 0。
但是,当计数器达到 5 时,网页仍然显示“Counts:4”并显示警报。更重要的是,标签的innerText已经变成了“Counts:5”。那么为什么 HTML 和实际网页之间存在不一致呢?它与异步操作有什么关系吗?
我可以添加一个setTimeout(function(){alert("Counter value: "+ totalCount)},1000);
来延迟警报。但这不是我的初衷。警报应始终在计数器达到 5 后立即弹出并显示为“Counts:5”。
let totalCount = 0;
function onload() {
document.getElementById("increment").addEventListener("click", onClick);
renderCounter();
}
function onClick() {
totalCount++;
renderCounter();
if (totalCount > 4) {
alert("Counter value: " + totalCount);
totalCount = 0;
renderCounter();
}
}
function renderCounter() {
let counts = document.getElementById("counter");
counts.innerText = "Counts: " + totalCount;
}
<body onload="onload()">
<header id="header">
<h1>Interesting tests</h1>
</header>
<section class="my-counter">
<p id="counter"></p>
</section>
<section id="increment-button">
<button type="button" id="increment"> +1 </button>
</section>
<script src="increment.js"></script>
解决方案
您确实需要 setTimeout,但不一定是 1 秒
- 渲染前不要重置
- 警报被阻止,因此界面没有机会更新
- 允许渲染,然后发出警报,然后再次渲染
- 使用 eventListener 而不是内联事件处理程序
let totalCount = 0;
window.addEventListener("load", function() {
document.getElementById("increment").addEventListener("click", onClick);
renderCounter();
})
function onClick() {
totalCount++;
renderCounter();
if (totalCount > 4) {
totalCount = 0;
setTimeout(function() {
alert("Counter value: " + totalCount);
renderCounter();
}, 10); // allow the interface to update
}
}
function renderCounter() {
let counts = document.getElementById("counter");
counts.innerText = "Counts: " + totalCount;
}
<header id="header">
<h1>Interesting tests</h1>
</header>
<section class="my-counter">
<p id="counter"></p>
</section>
<section id="increment-button">
<button type="button" id="increment"> +1 </button>
</section>
<script src="increment.js"></script>
推荐阅读
- java - 从没有api的网站检索数据
- javascript - 为什么我的“返回顶部”按钮在 Firefox 上失败?
- typescript - VUE:是否有可能没有冲突的属性名称数据?
- excel - 将错误作为运行时错误“-2147467259(800004005)”:自动化错误未指定错误
- r - 在约束和二元变量中使用函数进行约束优化
- javascript - 限制在全日历中创建事件
- asp.net - 页面加载一遍又一遍
- javafx - JavaFX:PopOver 窗口的鼠标事件 (ControlsFX)
- django - django api在连接到mysql时抛出500(内部服务器)错误
- python - 使用“编解码器”模块定义函数时遇到问题