开发者

how to control which parts the && applies to in an if statement

开发者 https://www.devze.com 2023-03-20 08:22 出处:网络
let say I have this if statement: if($(this).hasClass(\'rightnav\') | $(this).parent() == \'nav\' && $(this).pare开发者_StackOverflow中文版nt().parent() == \'section\')

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')

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号