1

For my question i'll need to first write some css.

.hide { display: none; }

Now, in jQuery which of the two examples below would be faster?

if ($('#a').is(':hidden')) {
    $('#a').show();
} else {
    $('#a').hide();
}

or

if ($('#a').hasClass('hide')) {
    $('#a').removeClass('hide');
} else {
    $('#a').addClass('hide');
}
4

3 回答 3

4

Manipulations with classes are faster than calling show/hide functions.

Here is the jsperf: http://jsperf.com/hide-or-class

于 2013-07-21T05:34:27.293 回答
0

I think you can try this code :

$('a').toggleClass('hide')

It makes the same thing that your codes but it is smaller. You can have a look to the documentation of the toggleClass.

于 2013-07-21T05:33:33.403 回答
0

what Lucas Willems told is correct. use toggleClass() function to reduce your code and it will much faster than using hide() and show() methods

于 2013-07-21T06:12:49.997 回答