开发者

'if' statements don't function correctly

I am writing some jQuery code that involves jumping from several functions. In one function, an 'if'-statement is used to select where the code will go next. The condition for the if statement is the value of开发者_Python百科 a variable that was passed from the previous function. So, to clarify, a function passes a variable to another function, which then goes to another function which is chosen based on the function it originated from.

Here is my code in JSFiddle: http://jsfiddle.net/VFVk7/

As you can see, when you click on any of the buttons, it goes to all of the optional functions from the If-statement, not just one. Does anyone know why this is happening? Thanks very much!


By writing if(origin = 'go1'), you are assigning 'go1' to the origin variable, and passing the result of that assignment (which is the string 'go1') to the if statement.
Since all non-empty strings are "truthful" in Javascript, this is equivalent to if (true), and all of the if statements execute.

You need to compare 'go1' to the origin variable by writing if (origin === 'go1').

Summary

  • The = operator assigns a value to a variable
  • The == operator performs a loose comparison (eg, true == '1', 8 == '8', 16 == '0x10', false == []).
  • The === operator performs a strict comparison. (none of the above examples are true with ===)


You have code like

if(origin = 'go1')

which assigns 'go1' to variable origin (and check if that's "true" -- which it is).
Try, instead:

if(origin == 'go1')

to compare instead of assigning.


Common problem. In Java it will give a compile error, in Javascript it will work just fine, probably not in the way you want it. = sign in Javascript does not perform equality operation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜