If语句永远不会到达else分支 - “if(x = y)” [英] If-statement never reaches else branch - "if (x = y)"
问题描述
我有这个奇怪的问题:
下面是一个JavaScript函数
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
}
它捕获了HTML元素选择的选项值并显示相应的消息......或者它应该是。无论选择如何,它总是显示1。
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.
另一方面,以下工作。
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?
推荐答案
条件语句使用称为等于运算符的双等号 -
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'
这篇关于If语句永远不会到达else分支 - “if(x = y)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!