Jquery “if this and if that” then do this

旧巷老猫 提交于 2019-12-21 03:37:32

问题


This should be so simple, but it's not working for me. I want to say:

If this doesn't have the class "current" AND if the body class does not equal "home", then do this....

Here is what I'm trying (among other things) to no avail. Only the first conditional works.

$(".nav1 > ul > li").mouseleave(function() {

    if ( (!$(this).hasClass("current")) || (!$(body).hasClass("home"))  ){
         $(this).find(".nav-overlay").show();   
    }

}); 

What am I doing wrong? Thank you!

UPDATE FOR CLARITY:

I only want to show ".nav-overlay" when the following conditions are true:

  1. You are not on the homepage (body class="home") AND
  2. The ".nav1 > ul > li" class does not equal "current"

回答1:


Try $("body") and &&:

   if ( (!$(this).hasClass("current")) && (!$("body").hasClass("home"))  ){
    //...

Or this way , it is shorter:

   if ( !$(this).is(".current") && !$("body").is(".home")  ){
     //...



回答2:


If body is not a variable, access it as a HTML tag: add quotes. Also, AND is && instead of || (that means OR):

if (!$(this).hassClass("current") && !$("body").hasClass("home")) {
    $(this).find(".nav-overlay").show();
}

If body is a jQuery object you can do directly ... && !$body.hashClass(...).



来源:https://stackoverflow.com/questions/18216291/jquery-if-this-and-if-that-then-do-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!