简体   繁体   中英

Ajax request on dismissal of twitter bootstrap alerts

I'm using the "alert" functionality from Twitter Bootstrap to display user notifications, like so:

<div class="notification alert alert-info">
 <button type="button" class="close" data-dismiss="alert">&times;</button>
 My message goes here
</div>

These notifications are persistent until the user dismisses them, so when the user clicks the "close" button I would like to fire off an ajax query to the server indicating that the notification should be permanently dismissed.

I'm using jQuery's on() function like so:

$(document).on('click', '.notification .close', function (e) {
    alert('hi!');
    console.log(e);
    e.preventDefault();
});

This works fine, but I'm wondering if there is there a "Bootstrappy" way of doing this?

In Bootstrap 3.0 you need to use namespaced event name:

$('.alert').bind('closed.bs.alert', function () {
        var id = $(this).data('some_id');
        $.get('closed.php?id='+id);
})

According to the Bootstrap docs on alerts , I'd bind to the closed or close event, which are custom to Bootstrap.

$(document).on('close', '.alert', function  () 
{
    var id = $(this).data('some_id'); 
    $.get('closed.php?id='+id);
});

there are two events exposed via the API:

  1. close - which is fired immediately
  2. closed - fires after all animations have completed. I'd opt for close - this way you do it immediately and if they navigate / close before the animation completes, it will still be hidden.

The data attribute is to be able to have the server side script differentiate between the alerts. The markup would be:

<div class="alert" data-some_id='foobar'>
    Close me!
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM