【问题标题】:How to make an alert appear after every button click, and disappear after 5 seconds?如何在每次单击按钮后出现警报,并在 5 秒后消失?
【发布时间】:2020-10-12 23:54:45
【问题描述】:

.JS

 var alert = document.getElementById('notify').style.display = 'block';
    setTimeout(function(){
      document.getElementById("notify").innerHTML="";
      },3000);

HTML

<div class="alert alert notify text-center" id="notify" role="alert">
  <i class="fa fa-check"></i> Saved!
</div>

目前,我的项目旨在让学生在制定特定学期的课程表时从他们的学生课程表中添加/删除课程。我有一个保存警报,我想在学生从购物车中添加或删除时出现。我还希望 sav 消息在 3 秒后消失。

【问题讨论】:

  • 你还没有说明你发布的代码有什么问题,但我会试一试:你为什么要清除#notifyinnerHTML?如果不重置其内容,您将无法重新使用#notify。你为什么选择这条路线而不是将style.display属性设置为block以外的属性?
  • 一开始你让#notify 可见,但是当你想让它消失时,为什么要清除它的innerHTML?您可以使用document.getElementById('notify').style.display = 'none';,与您之前所做的相反,使其可见。
  • 我们需要更多代码来诊断问题并提供可行的解决方案。

标签: javascript dom settimeout alert


【解决方案1】:

您应该将其 CSS 显示属性设置为“无”,而不是清空元素的 innerHTML。您还必须为按钮添加一个事件侦听器(您的 HTML 中明显缺少该事件侦听器)。

document.querySelector("#save").addEventListener("click", function(e){
  document.querySelector("#notify").style.display = "";
  setTimeout(function(){
    document.querySelector("#notify").style.display = "none";
  }, 3000);
});
<button id="save">Save</button>
<div class="alert alert notify text-center" id="notify" role="alert" style="display: none;">
  <i class="fa fa-check"></i> Saved!
</div>

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 2020-08-09
    • 2023-03-29
    • 2021-01-18
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2021-09-12
    相关资源
    最近更新 更多