最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery toggleClass with conditional - Stack Overflow

programmeradmin1浏览0评论

Does anyone know how to write the following in a neater, one line format? I'm sure it's possible but can't get very far with it.

if($('#myDiv').hasClass('hidden')){
   $('#myDiv').toggleClass('shown hidden');
}

Basically to only perform a toggle in one direction.

Many thanks,

Tom.

Does anyone know how to write the following in a neater, one line format? I'm sure it's possible but can't get very far with it.

if($('#myDiv').hasClass('hidden')){
   $('#myDiv').toggleClass('shown hidden');
}

Basically to only perform a toggle in one direction.

Many thanks,

Tom.

Share Improve this question asked Jun 15, 2012 at 11:41 Tom MillardTom Millard 5431 gold badge7 silver badges20 bronze badges 2
  • you want this in one line/.... it means – FrontEnd Expert Commented Jun 15, 2012 at 11:43
  • var result = $("#myDiv").hasClass("hidden") ? $('#myDiv').toggleClass('shown hidden') : false – Jagz S Commented Jun 15, 2012 at 11:45
Add a ment  | 

2 Answers 2

Reset to default 14
$('#myDiv.hidden').toggleClass('shown hidden');

Maybe you can just call $('#myDiv').removeClass('hidden').addClass('shown') (and the corresponding inverse). It'll remove .hidden if it's there, and add .shown if it doesn't have it yet.

发布评论

评论列表(0)

  1. 暂无评论