JQuery add/remove class not working the second time

I have a form to register user with some info. Upon submit, an ajax call is made which inserts the data into the DB, and returns a status code. Depending upon the status, I show a div. The div has an initial class "hidden", and a close button. Upon return from the php, I remove the "hidden" class and add the "alert-danger" or "alert-success" class.

Once the user clicks the close(x) button, I add the "hidden" class again, and check if the element has "alert-danger" or "alert-success" class and remove that as well. This works (or at least it hides) for the first time. However, the div doesn't show up the second time.

What is it that I am missing here?

Here's the div

<div class="alert alert-block fade in status hidden">
 <button type="button" class="close" data-dismiss="alert">&times;</button>
 <h4 class="message-head"></h4>   
 <p class="message"></p>   
</div>

Here's the code run upon success/error

$.ajax({
  type:"post",
  url:"register.php",
  data:"name="+name+"&phone="+phone+"&email="+email+"&msg="+msg,
  success:function(data){

  if(data.status === 'success'){
     //show the status msg
     $('.message-head').text("Thank You");
     $('.message').text("Your Request has been taken");
     $(".status").removeClass("hidden").addClass('alert-success');

      }else {
     $('.message-head').text("Sorry");
     $('.message').text("There is some Error. Please Try Again Later");
     //alert(data.status);
     $('.status').removeClass('hidden').addClass('alert-danger');
}}

And here's the code for the close button click

$('.close').click(function(){
 if ( $('.status').hasClass("alert-danger") ) {
 $('.status').removeClass("alert-danger").addClass("hidden");
}else if ( $('.status').hasClass("alert-success") ) {
 $('.status').removeClass("alert-success").addClass("hidden");
}
});

I put together a simple fiddle for you

Link: http://jsfiddle.net/qyyegwhu/1/

Are you including the class .hidden in css:

.hidden{
    display: none;
}

I'm having trouble replicating the issue otherwise?


I'm not completely sure, but I believe that closing Bootstrap alerts should work out of the box when you open them with the bootstrap JS Function.

This should work for opening:

$('.message-head').text("Thank You");
$('.message').text("Your Request has been taken");
$('.alert').alert();

The code for closing the alert is not needed, because the alert is closed automatically like in the bootstrap example http://getbootstrap.com/javascript/#alerts

EDIT: Another approach would be to create the alert with javascript. This would be the solution for both of your problems. (see JSFiddle )

链接地址: http://www.djcxy.com/p/69732.html

上一篇: Yii中的自定义小部件

下一篇: JQuery添加/删除类不工作的第二次