jQuery if 和 else 语句检查是否有类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16182556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:37:52  来源:igfitidea点击:

if and else statement check if has class

jqueryif-statement

提问by NodeDad

I cant seem to figure out whats going on here... Im kind of half asleep, really trying to get this last thing done before i go to bed lol.

我似乎无法弄清楚这里发生了什么......我有点睡着了,真的想在睡觉前完成最后一件事,哈哈。

My goal: Click someone, then check if it has the class, if not, then add it, then remove it once the 1 second animation is complete. Right now im getting unexpteced identifier on the 3rd line down. (removeClass)

我的目标:单击某人,然后检查它是否有类,如果没有,则添加它,然后在 1 秒动画完成后将其删除。现在我在第三行得到了意外的标识符。(删除类)

Note: the slamedownclass is a keyframe

注意:slamedown类是关键帧

$('#accountloginsignup h1').click(function() {
  if ($('#takeonebar').hasClass('slamdown')){
    $('#takeonebar')removeClass('slamedown');
  } else {
    $('#takeonebar').addClass('slamdown');
  }
});

回答by Arun P Johny

.toggleClass()is for this specific purpose

.toggleClass()用于此特定目的

From the doc

从文档

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

根据类的存在或 switch 参数的值,从匹配元素集中的每个元素中添加或删除一个或多个类。

$('#accountloginsignup h1').click(function() {
    $('#takeonebar').toggleClass('slamdown');
});

There is a typo

有一个错字

$('#accountloginsignup h1').click(function() {
    if ($('#takeonebar').hasClass('slamdown')){
        $('#takeonebar').removeClass('slamdown');  /missing . before removeClass
    } else {
        $('#takeonebar').addClass('slamdown');
      }
});

回答by Ben McCormick

You had a few typos:

你有几个错别字:

$('#accountloginsignup h1').click(function() {
        if ($('#takeonebar').hasClass('slamdown')){
            $('#takeonebar').removeClass('slamdown');
        } else {
            $('#takeonebar').addClass('slamdown');
          }
        });

but what you really want is $('#takeonebar').toggleClass('slamdown')

但你真正想要的是 $('#takeonebar').toggleClass('slamdown')

jquery Docs

jQuery 文档

回答by amjayesh07

this helped me while working with hasclass

这在使用 hasclass 时帮助了我

$( "div" ).click(function() {

$( "div" ).click(function() {

if ( $( this ).hasClass( "protected" ) ) {

    $( this )
        .animate({ left: -10 })
        .animate({ left: 10 })
        .animate({ left: -10 })
        .animate({ left: 10 })
        .animate({ left: 0 });

}

});

});

reference link

参考链接