How to toggle a bootstrap alert on and off with button click?

前端 未结 9 887
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 21:21

I want to display an alert box multiple times with a button click event without having to refresh the page but the alert box only shows up once. If I want to show the alert box

相关标签:
9条回答
  • 2021-01-30 21:59

    Actually you should consider using something like this :

    $('#the-thing-that-opens-your-alert').click(function () {
      $('#le-alert').addClass('in'); // shows alert with Bootstrap CSS3 implem
    });
    
    $('.close').click(function () {
      $(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
    });
    

    As bootstrap fade/in uses CSS3 instead of Jquery hide/show in full Javascript. My point is that on mobile devices, CSS3 is faster than Js.

    And your HTML should looks like this:

    <a id="the-thing-that-opens-your-alert" href="#">Open my alert</a>
    
    <div id="le-alert" class="alert alert-warn alert-block fade">
      <button href="#" type="button" class="close">&times;</button>
      <h4>Alert title</h4>
      <p>Roses are red, violets are blue...</p>
    </div>
    

    And this is pretty cool ! Check it in jsFiddle =)

    0 讨论(0)
  • 2021-01-30 22:03

    You can add .hidden class to you alert and then toogle it. See: JSFiddle

    HTML

    <a id="show-my-alert" href="#">Show Alert</a>
    
    <div id="my-alert" class="alert alert-warning hidden" 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>
    

    JavaScript

    $("#show-my-alert, .close").click(function() {
        $("#my-alert").toggleClass("hidden");
    });
    
    0 讨论(0)
  • 2021-01-30 22:04

    I've had the same problem: just don't use the data-dismiss from the close button and work with JQuery show() and hide():

    $('.close').click(function() {
       $('.alert').hide();
    })
    

    Now you can show the alert when clicking a button by using the code:

    $('.alert').show()
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题