how to control which parts the && applies to in an if statement
let say I have this if statement:
if($(this).hasClass('rightnav') | $(this).parent() == 'nav' && $(this).pare开发者_StackOverflow中文版nt().parent() == 'section')
How can I tell the script that the && should apply after the | and not the entire if? Thanks! this is really confusing me :s
if(($(this).hasClass('rightnav') | $(this).parent() == 'nav') && $(this).parent().parent() == 'section')
and shouldn't it be ||
instead of |
?
Note that you should have ||
(logical-or) instead of |
(bitwise-or).
Second, logical-and (&&
) has higher precedence than logical-or (||
). See numbers 13 and 14 in the list of precedence here: https://developer.mozilla.org/en/JavaScript/Reference/operators/operator_precedence
But if you're not sure, or to help out maintenance coders who come along later, parentheses are a good choice. Whatever is in the parens will get executed first.
I think this should do it:
if(($(this).hasClass('rightnav') || $(this).parent() == 'nav') && $(this).parent().parent() == 'section')
精彩评论