OR and AND combinations inside if-statement

萝らか妹 提交于 2019-12-24 10:59:33

问题


I have this selector:

$('ul:not(.sub-menu) > li, ul.sub-menu > li:last-child').not(':has(ul.sub-menu)');

which gets these elements:

  1. Every direct li descendant whose parent is not .sub-menu (unless it's the last, cf. 2.)
  2. Every last li element of an ul.sub-menu
  3. Exclude all li's that are parent to a ul.sub-menu

Now, I want to use this in an if-statement, which is inside a hover-function. In other words, it's got to be relative to that list item instead of being the list item.

Something like this:

$("nav li").hover(function () {
  var $this = $(this); 
  if (($this.parent("ul:not(.sub-menu)") || ($this.parent("ul.sub-menu") && $this.is(":last-child"))) && $this.not(":has(ul.sub-menu)")) {
     // do something
  }
});

But this does not work. I think it has something to do with combining the OR and AND selectors inside an if-statement, but I can't seem to debug it: the code above selects all list items without a distinction.


回答1:


$this.parent("ul:not(.sub-menu)") is never falsy, even if the set is empty.

Use $this.parent("ul:not(.sub-menu)").length instead in your condition.

The whole if statement would thus look like this :

if (
    (
        $this.parent("ul:not(.sub-menu)").length
        || ( $this.parent("ul.sub-menu").length && $this.is(":last-child") )
    ) && !$this.hasClass("sub-menu")
) {
     // do something
}

Details :

if ($('#a')) { // always verified

if ($('#a').length>0) { // verified if there is an element with id a

if ($('#a').length) { // identical to last one

As written by the MDN :

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined



来源:https://stackoverflow.com/questions/14293673/or-and-and-combinations-inside-if-statement

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