Twitter Bootstrap. 记住警告关闭操作

6

我曾试图记住 Twitter Bootstrap 警告框的关闭操作,遵循这篇文章(Using Bootstrap, have alert box remember close action)。

我希望用户在关闭警告框后重新加载页面时不能再看到它。

我知道我必须将状态存储到 cookie 中,因此我使用了上面示例中建议的 JQuery 函数,但它不起作用。我做错了什么吗?

示例 -> http://jsfiddle.net/kFy5y/

提前致谢!

jQuery(function( $ ){

    // Check if alert has been closed
    if( $.cookie('alert-box') === 'closed' ){

        $('.alert').hide();

    }

     // Grab your button (based on your posted html)
    $('.close').click(function( e ){

        // Do not perform default action when button is clicked
        e.preventDefault();

        /* If you just want the cookie for a session don't provide an expires
         Set the path as root, so the cookie will be valid across the whole site */
        $.cookie('alert-box', 'closed', { path: '/' });

    });

});

警报

<div class="alert alert-info fade in">            
            <button type="button" class="close" data-dismiss="alert">×</button>
            <strong> ALERT BODY</strong>
</div>
2个回答

3
你正在使用 $.cookie('alert-box') , 这不是标准的jQuery函数, 而是在类似 jquery-cookie 的库中实现的一种方法。
因此,您需要添加此库或类似的库才能使用jQuery保存Cookies。

谢谢你的回答。我已经添加了jquery.cookie.js但还是不起作用:( 更新后的fiddle -> http://jsfiddle.net/kFy5y/1/ - ɐsɹǝʌ ǝɔıʌ
在开头删除 $(".alert").alert()$(x).alert() 也不是 jQuery 函数。将其删除,就可以了。请注意,当您单击关闭按钮时,它会设置您的 cookie。如果您刷新页面,则该 div 将被隐藏。Fiddle:http://jsfiddle.net/rrikesh/kFy5y/3/ - RRikesh

1
这里有一个通用的解决方案,适用于每个带有ID的警报在每个页面上。

//////////////////////////////////
    //remember close BS alert

    function showUnDismissedAlerts(){
        //if there is no localStorage, just show all alerts and return
        if (!localStorage.getItem(`dismissedAlerts_${document.title}`)) {
            $('.alert').show()
            return;
        }
        //get dismissed alert ID's
        let dismissedAlerts = JSON.parse(localStorage.getItem(`dismissedAlerts_${document.title}`))
        //look for each alert if it was dismissed
        $('.alert').map((index, el) => {
            //get the alert ID
            let alertId = $(el).attr('id')
            //if there is no ID, return (next alert)
            if (!alertId) return;
            //assuming the alert isn' dismissed
            let dismissed = false
            for (let i = 0; i < dismissedAlerts.length; i++) {
                //if the alert is present, it was dismissed, therefore set dismissed to true and exit for
                if (alertId == dismissedAlerts[i]) {
                    dismissed = true
                    break;
                }
            }
            //if alert isn't dismissed, show it
            if (!dismissed) $(el).show()
        })
    }

    //fires if there are alerts on page
    if ($('.alert').length > 0) {
        $('.alert').on('click', '.close', function (e) {
            e.preventDefault()
            //get alert element
            let parent = $(this).parent()
            //get alert ID
            let id = $(parent).attr('id')
            //return if no ID is defined
            if (!id) return;
            //get all dismissed alerts, based om localStorage. The document title is in key to prevent long data arrays
            if (!localStorage.getItem(`dismissedAlerts_${document.title}`)) {
                //if storage doesn't exists, add it with the dismissed alert ID
                localStorage.setItem(`dismissedAlerts_${document.title}`, JSON.stringify([id]))
            } else {
                //localStorage exists, so get it and parse it to an array
                let alerts = JSON.parse(localStorage.getItem(`dismissedAlerts_${document.title}`))
                //assuming the alert isn't already dismissed
                let alreadyDismissed = false
                //loop trough dismissed alerts and find out if there is a double
                alerts.map(alertId => {
                    //if id is already there, return
                    if (alertId == id) {
                        alreadyDismissed = true
                        return;
                    }
                })
                //if id alert ID isn't added, so add it an store the new dismissed alerts array
                if (!alreadyDismissed) {
                    alerts.push(id)
                    localStorage.setItem(`dismissedAlerts_${document.title}`, JSON.stringify(alerts))
                }
            }
        })

        //show all the undismissed alerts
        showUnDismissedAlerts()
    }
.none{
  display: none;
}
<!-- css -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="alert alert-info alert-dismissible none" role="alert" id="my_alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">×</span>
  </button>
  <strong>I'm a alert</strong>
</div>

<!-- script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>


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