首页 > 解决方案 > 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>

标签: javascripthtmldom

解决方案


您确实需要 setTimeout,但不一定是 1 秒

  1. 渲染前不要重置
  2. 警报被阻止,因此界面没有机会更新
  3. 允许渲染,然后发出警报,然后再次渲染
  4. 使用 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>


推荐阅读