每次访问显示一次警报

display alert once per visit

我正在研究如何在用户第一次访问网站时显示一次警告消息。在按下关闭按钮之前,该消息应该在每个页面上都可见。我将代码放在 _Layout.cshtml 中,但它不起作用,我习惯这样做。

你能指出我的错误吗?

@if(Session["Alert"] != "Confirmed")
{
    <div id="myAlert" class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <strong>Warning!</strong> Better check yourself, you're not looking too good.
    </div>
}

<script type="text/javascript">
$(document).ready(function () {
    $("#myAlert").on('closed.bs.alert', function () {
        sessionStorage.Alert = "Confirmed";
    });
});
</script>

每次重新加载 site/page 时都会显示警报。看起来好像在按下警报关闭按钮时没有执行脚本。更重要的是会话["Alert"]没有设置。

sessionStorage 和服务器端 Session 不是一回事!您不能将值设置为 sessionStorage 并期望从服务器端获取它 Session。所以你有两个选择:

1.使用服务器端 Session

更改您的 javascript 代码以向 mvc 操作发送 ajax 请求,然后将 Session["Alert"] 设置为 "Confirmed"。

2。使用 sessionStorage

而不是使用 @if(Session["Alert"] != "Confirmed"),您检查 sessionStorage 文档准备好决定是否显示警报。

第二个需要最少的代码才能更改。以下代码将起作用:

<div id="myAlert" style="display:none" class="alert alert-warning alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $(document).ready(function () {
            // If not 'Confirmed', show #myAlert
            if (sessionStorage.Alert !== 'Confirmed') {
                $('#myAlert').show();
            }
        });

        $('#myAlert .close').click(function () {
            // Set 'Alert' to 'Confirmed' when user click the close button
            sessionStorage.Alert = "Confirmed";
            $(this).closest('#myAlert').hide();
        });
    });
</script>

在 Page_Load sub 后面的代码中,我设置了我的会话变量:

    If IsNothing(Session("visit")) Then
        Session("visit") = "no"
    Else
        Session("visit") = "yes"
    End If

在 body 标签中,我放置了一个 onload 事件:

onload="showAlert();"

然后我添加了这个小 javascript 函数:

    function showAlert() {

        var visit = '<%= Session("visit")%>';
        if (visit == 'no') {
            document.getElementById('id01').style.display = 'block';
        }            
    }

访问者第一次访问我的登录页面时,他们会看到我保存在 div 中的欢迎提示,id='id01'。在这次访问中,他们下次访问登录页面时,会话在页面加载时更改为是,他们不会再看到警报。