I want to click on a button, a div appears, when clicking the same button it should disappear.
Actual开发者_StackOverflowly only appearing works, how to hide it again?
Skript:
$('#button').click(function() {
$('#ui-block-a').removeClass('visuallyhidden').addClass('ui-block-a'), function(){
$('#ui-block-a').addClass('visuallyhidden').removeClass('ui-block-a');
};
});
HTML:
<div class="visuallyhidden" id="ui-block-a">
<ul data-role="listview" data-filter="true" id="nav"></ul>
</div>
Here is try to use a callback, but it is not working...
If the classes are correctly set from the beginning, you can use .toggleClass()
[docs]:
$('#ui-block-a').toggleClass('visuallyhidden ui-block-a');
Otherwise, if you explicitly want to add/remove classes, you can use .toggle()
:
$('#button').toggle(function() {
$('#ui-block-a').removeClass('visuallyhidden').addClass('ui-block-a');
}, function(){
$('#ui-block-a').addClass('visuallyhidden').removeClass('ui-block-a');
});
Why your code does not work:
You are not setting up a callback. You are executing two statements via the comma operator. The first part ($('#ui-block-a').addClass('...').removeClass('...')
) will be executed as expected. The second part (function() {...}
) will be evaluated as function expression and the result, a function, will be returned as overall result of the statement. But you are not assigning the result to anything, so it is just silently ignored.
E.g. if you'd do
// form is like `var foo = x, y;`
var foo = $('#ui-block-a').removeClass('...').addClass('...'), function(){
$('#ui-block-a').addClass('...').removeClass(...');
};
then foo
would refer to the function
function() {
$('#ui-block-a').addClass('...').removeClass('...');
}
But that is not what you want anyway. So putting a function there is legal, but has not special meaning and thus no effect.
Use toggleClass
, sometimes toggleClass
can be a bit temperamental so use an if statement and and variable.
in sudo code:
variable = 0
if variable = 0
{
Show Div
variable = 1
}
else if variable = 1
{
Hide Div
variable = 0
}
精彩评论