这是我当前的if / else语句:
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');
}
是否有更短的方式来写所有这些?看起来......超重。 :)
答案 0 :(得分:7)
答案 1 :(得分:2)
IMO这是最干净,最清晰的解决方案:
var current_class = $(this).closest("article");
if (current_class.hasClass('opened'))
{
current_class.removeClass('opened').addClass('closed');
}
else
{
current_class.removeClass('closed').addClass('opened');
}
答案 2 :(得分:0)
可能是这样的:
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');
答案 3 :(得分:0)
$(this).closest("article").toggleClass('opened').toggleClass('closed');