Here's my current if/else statement:
var current_class = $(this).closest("article").attr("class")
if (current_class == 'opened')
{
$(this).closest("article").removeClass('opened');
$(this).closest("article").addClass('closed');
}
else
{
$(this).closest("article").removeClass('closed');
$(this).closest("article").addClass('opened');
}
Is there a shorter way to write all of that? Just seems...overweig开发者_如何转开发ht. :)
Use
.toggleClass()
Here is an example http://api.jquery.com/toggleClass/
IMO this is the cleanest and still clearest solution:
var current_class = $(this).closest("article");
if (current_class.hasClass('opened'))
{
current_class.removeClass('opened').addClass('closed');
}
else
{
current_class.removeClass('closed').addClass('opened');
}
maybe something like:
var current = $(this).closest('article'); // no need to run the selector over and over
var current_class = current.attr('class');
current.removeClass('opened closed').addClass(current_class=='opened'?'closed':'opened');
$(this).closest("article").toggleClass('opened').toggleClass('closed');
精彩评论