Twitter Bootstrap。记住警报关闭行动

时间:2013-04-02 09:54:00

标签: jquery cookies twitter-bootstrap alert

我试图记住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 个答案:

答案 0 :(得分:3)

您使用的$.cookie('alert-box')不是标准的jQuery函数,而是在jquery-cookie等库中实现的方法。

所以你需要添加这个库或类似的库,以便能够使用jQuery保存cookie。

答案 1 :(得分:0)

这是一种通用解决方案,适用于每个带有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>