开发者

jQuery .toggle(showOrHide): implementation question

I'm having a button toggle whether a referenced div is visible or not. Originally, I was using the code:

$('#search-options-btn').click(function() {
    if ($('#search-options').is('.hidden')) {
        $('#search-options').removeClass('hidden');
    } else {
        $('#search-options').addClass('hidden');
    }
});

However, in an attempt to find cleaner code, I came across the jQuery toggle() method, which according to the API has a method implementation

.toggle( showOrHide )    
showOrHide: A Boolean indicating whether to show or hide the elements.

This description leads me to believe this is a shortcut implementation method for showing or hiding 开发者_JAVA百科by passing the...identifier? showOrHide into the toggle() method.

Of course, attempting this:

$('#search-options-btn').click(function() {
    $('#search-options').toggle(showOrHide);
});

yields an error in my firebug console:

showOrHide is not defined
[Break On This Error] $('#search-options').toggle(showOrHide); 

I've also tried defining showOrHide as a boolean initialized to false; the error goes away, but the issue is not fixed.

According to the jQuery online API, this is supposed to be equivalent to

if ( showOrHide == true ) {
  $('#foo').show();
} else if ( showOrHide == false ) {
  $('#foo').hide();
}

unless I'm completely missing how this works. Can anyone fill me in on what I'm doing wrong here? I haven't been able to find a similar implementation.


you should just need toggle(), nothing else.

$('#search-options-btn').click(function() { $('#search-options').toggle(); });


showOrHide is the internal name. You pass in a bool:

$('#...').showOrHide(true)

if you want the item to be visible, false if you want it hidden.


Its just toggle between class and not with boolean..

$('#search-options-btn').click(function() { $('#search-options').toggle('yourClassName'); });

If yourClassName is found, then it will remove the same, otherwise it will add it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜