addClass & removeClass not working
I have a menu, it should work as a click menu, so when clicking the button a menu will appear, and when clicking the button again, the menu should开发者_StackOverflow中文版 disapear, but i cant get it to work ?
I've got this script
<script type="text/javascript">
$(document).ready(function() {
$('#dropdown').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown2");
$('#dropmenu').addClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
$('#dropdown2').click(function(){
setTimeout(function(){
$('#dropdown').attr("id", "dropdown");
$('#dropmenu').removeClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
})
});
</script>
It works fint when adding the class, but then when im clicking the button again, it wont remove the class "open"
After you write $('#dropdown').attr("id", "dropdown2");
, there is no #dropdown
element for the code in the second handler to match.
Also, when you bind the second handler, there is no #dropdown2
element yet. (live
events would solve that issue)
Instead, you should use the toggle
event, which allows you to bind multiple click
handlers that will execute every other click.
For example:
$(document).ready(function() {
$('#dropdown').toggle(
function() {
setTimeout(function(){
$('#dropdown').addClass("open")
.fadeIn('fast');
}, 500);
},
function() {
setTimeout(function(){
$('#dropdown').removeClass("open")
.fadeOut('fast');
}, 500);
}
);
});
The reason it isn't working is that the dropdown2 id doesn't exit when you register the click handler. You could use to live to overcome this, but it is better to use classes:
$(document).ready(function() {
$('#dropdown').click(function(){
if (!$(this).hasClass("open")) {
setTimeout(function(){
$('#dropmenu').addClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
} else {
setTimeout(function(){
$('#dropmenu').removeClass("open");
//$('#dropmenu').fadeIn('fast');
},500);
}
})
});
I updated above code, working good for me. Please try this,
$(document).ready(function(){
$("#loginlink").click(function(){
$('.container .col-sm-6 ul li .dropdown-menu').first().toggle(
function() {
setTimeout(function(){
$('.container .col-sm-6 ul li').first().addClass("open").fadeIn('fast');
});
}
);
if(("#loginformstarthere").length){
$(".container .col-sm-6 ul li .dropdown-menu").first().append( "hello");
}
});
精彩评论