简体   繁体   中英

jQuery function associated with Bootstrap button is executed only once

I'm following a tutorial using Bootstrap 3. So far so good, except for a non-expected behavior: when I click a button associated with a jQuery function, the alert gets displayed fine. However, once I dismiss it, clicking the button again doesn't do anything, that is, looks like it's a no-op.

For brevity, I'll include the relevant sections. I have the following <div> :

    <div class="row" id="bigCallout">
        <div class="col-12">

            <div class="alert alert-success alert-block fade in" id="successAlert">
                <button type="button" class="close" data-dismiss="alert">&times;</button>
                <h4>Success!</h4>
                <p>You just made this element display using jQuery.</p>
            </div>

        </div>
    </div> <!-- end bigCallout -->

Below I include my JS file:

<!-- Custom JS -->
<script src="includes/js/script.js"></script>

The JS file mentioned above contains this only function:

$(function() {

   $('#alertMe').click(function(e) {

       e.preventDefault();

       $('#successAlert').slideDown();

   });

});

Why is the function being executed only the first time the button is clicked? Thanks!

When you rely on the data-dismiss="alert" which dismisses/closes the alert, the alert is actually removed from the data model. Therefore, when you click to attempt to slideDown the element again, that element no longer exists.

To get the desired behavior to re-use an alert message that has been "dismissed", you'll have to remove your data-dismiss and respond to the click event on the close button to slideUp or hide the element. Then your subsequent slideDown code will find the DOM elements successfully.

[EDIT] Here is a JSFiddle: http://jsfiddle.net/de4qkoe5/

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