Can't make multiple if conditions in JavaScript?

前端 未结 6 577
一整个雨季
一整个雨季 2021-01-28 23:15

I have absolutely no idea why this is not working. Makes no sense to me.

This returns a \"syntax error: parse error\":

if ($(this).attr(\"id\") === \'se         


        
相关标签:
6条回答
  • 2021-01-28 23:21

    There are three different operators at play:

    • =: assignment
    • ==: equality
    • ===: strict equality

    = actually modifies a variable, so you shouldn't use it inside if statements. That is, you should use ... || opening == true) instead of ... || opening = true).

    0 讨论(0)
  • 2021-01-28 23:27

    In JavaScript = is used to assign values, while == and === are used to compare them.

    When you put opening = true in your if statement, you aren't checking if opening is true, you are setting opening to true. Try using == instead.

    For example,

    var x = 5;
    if (x == 10) {
        alert("x is 10");
    } else {
        alert("x isn't 10");
    }
    

    will display "x isn't 10", while

    var x = 5;
    if (x = 10) {
        alert("x is 10");
    } else {
        alert("x isn't 10");
    }
    

    will display "x is 10".

    0 讨论(0)
  • 2021-01-28 23:27

    You have an error in your condition

    if ($(this).attr("id") === 'search' || opening = true) return false;
    

    should be

    if ($(this).attr("id") === 'search' || opening == true) return false;
    

    the problem is with the equals sign

    = is different to ==

    the first one is the assignment operator. the second one is for comparison

    0 讨论(0)
  • 2021-01-28 23:38

    the first example should read:

    if ($(this).attr("id") === 'search' || opening == true) return false;
    

    and the second:

    if (1 == 1 && 2 == 2) { return false; }
    

    Note the double equals (==) sign for logic equals is not the same as the single equals (=) sign, that handles variable assignment.

    0 讨论(0)
  • 2021-01-28 23:41

    My guess is that === does not exist. == is for testing equality

    so if ($(this).attr("id") === 'search' || opening == true) return false; should be if ($(this).attr("id") == 'search' || opening == true) return false;

    0 讨论(0)
  • 2021-01-28 23:42

    When you test like this:

    opening=true;
    

    What you are really doing is setting opening to the value of true. Use == instead.

    Finally, order of operations, even if correct, can get confusing. Put parenthesis around each part of the comparison.

    if (($(this).attr("id") === 'search') || (opening == true)) return false;
    
    0 讨论(0)
提交回复
热议问题