问题
I have this weird problem:
Below is a JavaScript function
function calculateSum()
{
var e2 = document.getElementById('hotel_names');
var selValue2 = e2.options[e2.selectedIndex].value;
if (selValue2='1')
{
alert("helloworld");
}
else
{
alert("byeworld");
}
//function closes
}
It captures the option value of an HTML element selection and show the appropriate message...or it should be. The thing is it always shows 1 no matter the selection.
On the other hand the following works.
function calculateSum()
{
var e2 = document.getElementById('hotel_names');
var selValue2 = e2.options[e2.selectedIndex].value;
alert(selValue2);
}
The second function shows the correct number each time you select an option from the selection. Any ideas why the first one does not work?
回答1:
Conditional statements use double equals sign called an equality operator -
if (selValue2 == '1'){
...
}
By using only one what you are essentially doing is assigning a value to the variable. This is called an assignment operator.
selValue2 = '1'
回答2:
You need an equality operator. You're using an assignment operator. Equality is
selValue2 == '1'
assignment is
selValue2 = '1'
回答3:
Just a small point to add to the other answers. I'd recommend using ===
instead of ==
for comparisons.
It checks both the value and the type of the parameters being compared and is often quicker.
来源:https://stackoverflow.com/questions/14369591/if-statement-never-reaches-else-branch-if-x-y