问题
I have this selector:
$('ul:not(.sub-menu) > li, ul.sub-menu > li:last-child').not(':has(ul.sub-menu)');
which gets these elements:
- Every direct
li
descendant whose parent is not.sub-menu
(unless it's the last, cf. 2.) - Every last li element of an
ul.sub-menu
- Exclude all
li
's that are parent to aul.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