Reputation: 1713
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 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!
Upvotes: 1
Views: 184
Reputation: 41097
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.
Upvotes: -2
Reputation: 887453
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')
.
=
operator assigns a value to a variable==
operator performs a loose comparison (eg, true == '1'
, 8 == '8'
, 16 == '0x10'
, false == []
).===
operator performs a strict comparison. (none of the above examples are true with ===
)Upvotes: 10
Reputation: 881635
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.
Upvotes: 6