如何使Javascript警告框只显示一次?

7

我很不擅长 Javascript,但不幸的是,我需要完成一项任务。我需要一个Javascript警告框只显示一次——不是每个浏览器会话一次,而是只显示一次。我正在为一个学校竞赛项目工作;警告将涉及到Internet Explorer与我的网站不兼容,建议使用Chrome或Firefox。然而,我不想用弹出窗口打扰评委,所以它只出现一次是最好的。我在网上找到了下面显示的代码,但我不能使它正确地工作。这可能是像括号缺失这样简单的问题——再次说明,我不擅长Javascript,只懂HTML和CSS。 :P 如果推荐其他代码来执行我的请求,那么请提出建议!感谢大家!

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<!--[if IE]>    
    <script type="text/javascript">
        $(document).one(function() { alert("You are using Internet Explorer to view this webpage.  Your experience may be subpar while using Internet Explorer; we recommend using an alternative internet browser, such as Chrome or Firefox, to view our website."); } );
    </script>
<![endif]-->

4
COOKIES或本地存储!了解它们。 - epascarello
1
为了澄清,即使法官稍后再查看该网站,您也只希望警报显示一次,是这样吗?还是仅在加载此页面时显示一次? - DA.
1个回答

10

one并不是你需要的,因为页面刷新会覆盖所有的“内存”。

你最可能需要的是localStorage,如果你使用的是Internet Explorer 8之前的版本,则可以使用cookies:

    <script type="text/javascript">
        var alerted = localStorage.getItem('alerted') || '';
        if (alerted != 'yes') {
         alert("You are using Internet Explorer to view this webpage.  Your experience may be subpar while using Internet Explorer; we recommend using an alternative internet browser, such as Chrome or Firefox, to view our website.");
         localStorage.setItem('alerted','yes');
        }
    </script>

编辑:

对于IE 8及以前的版本,由于不支持localStorage,您需要使用cookie。这是完全相同的概念,只是方法不同。查看此问题了解在页面上实现cookie的方式。

示例中复制代码后,您应该有两个函数 - createCookie()getCookie()

var createCookie = function(name, value, days) {
....
//copy it from the other question
..
}

function getCookie(c_name) {
....
//copy it from the other question
..
}

<!--[if IE]>  
    <script type="text/javascript">
                var alerted = getCookie('alerted') || '';
                if (alerted != 'yes') {
                 alert("You are using Internet Explorer to view this webpage.  Your experience may be subpar while using Internet Explorer; we recommend using an alternative internet browser, such as Chrome or Firefox, to view our website.");
                 createCookie('alerted','yes',365);//cookies expires after 365 days
                }
            </script>
<![endif]-->
希望这能有所帮助!

2
我建议使用cookies而不是localstorage……因为我们要处理IE。 - DA.
@DA 和 @gnack,根据你们的评论,我更新了我的答案...不太想从头编写整个 setCookie()getCookie() :) - dev7
你可以使用一个localStorage polyfill(回退)来支持所有浏览器:https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-storage-localstorage-and-sessionstorage - David d C e Freitas
@Ben 修改了我的答案以实现 cookies。应该可以工作了! - dev7
你的浏览器启用了cookie吗?我建议你学习一些如何使用console.log调试应用程序并查看它在哪里中断... - dev7
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接