javascript - 如何在一段时间后自动隐藏消息 "You have been subscribed to our newsletter "?

标签 javascript asp.net ajax contact-form ajaxform

消息“您已订阅我们的时事通讯”本身不会自动隐藏,每次需要在页面中输入新条目时我都必须刷新页面,而且我希望表单区域为空白。 see in the below image i want to hide that subscription message after sometime on its own and email area should also be blank to get a new entry.

 <script type="text/javascript">
function doSubscribe() {
    var subscriberEmail = document.getElementById("subscriberEmail").value;
     
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "subscribe-newsletter.php", true);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     
    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
           
        }
        
    };

    ajax.send("subscriberEmail=" + subscriberEmail);
    return false;
}

应该怎么做才能使消息自动隐藏而不刷新页面,并且电子邮件区域也应该为空白。

最佳答案

您需要对 onreadystatechange 函数进行一些小更改:

现在

if (this.readyState == 4 && this.status == 200) {
      document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
}

大多数

if (this.readyState == 4 && this.status == 200) {
    var element = document.getElementById("subscribe-message");
    element.innerHTML = "You have been subscribed to our newsletter.";
    setTimeout(() => {
        element.innerHTML = "";
    }, 3000) // Put your delay in milliseconds ex: 3 seconds is 3000 milliseconds
}

setTimeout() 方法在指定的毫秒数后调用函数或计算表达式。该函数仅执行一次。

关于javascript - 如何在一段时间后自动隐藏消息 "You have been subscribed to our newsletter "?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65867342/

相关文章:

javascript - 如何退出 JavaScript 中的无限循环?

javascript - Node.js - 如何将变量备份到文件并在服务器重新启动时重新获取它?

javascript - 如何保持一个div的右边缘与另一个div的右边缘相同

asp.net - 使用 DataTable 数据源搜索 Gridview

javascript - 如何使用 vue.js 获取下拉列表中的选定值?

c# - 如何在运行时在 GridView 中添加动态文本框?

ASP.NET Ajax : close window after Ajax call?

Javascript/jQuery 对象范围问题

javascript - ajax完成后获取一个变量

javascript - 使用 Ajax .append() 时 jQuery 淡入内容