如果情况总是如此,但可能是假的 [英] If case is always true, but probably false
问题描述
我有一个简单的表格下拉菜单,我想根据选择值显示不同的内容。我有一个名为 connectiontype 的变量,它带有来自下拉列表的正确值,但if / else语句似乎不起作用 - 我总是以红色结束。有什么想法?
I have a simple form drop-down, and I want to display something different depending on the selection value. I have a variable called connectiontype that comes in with the correct values from the drop down, but the if/else statements don't seem to work - I always end up with red. Any ideas as to why?
Add
<select name="connection_type" id="connection_type">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
connection
<input type="button" value="Go" onclick="javascript:addDataSource();">
这是javascript,简化。
Here's the javascript, simplified.
function addDataSource() {
DSN++;
connectiontype = $("#connection_type").val();
if (connectiontype = 'red') {
var html = 'Red';
} else if (connectiontype = 'green') {
var html = 'Green';
} else {
var html = 'Blue';
}
addElement('DSN', 'div', 'DSN-' + DSN, html);
console.log(DSN);
}
function addElement(parentId, elementTag, elementId, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
推荐答案
您正在使用 =
(赋值)而不是 ==
(比较)。
You are using =
(assignment) instead of ==
(comparison).
if (connectiontype == 'red') {
...
} else if (connectiontype == 'green') {
...
}
当你有作业时,例如: lhs = rhs
整个表达式返回 rhs
。所以:
When you have an assignment, eg: lhs = rhs
the whole expression returns whatever rhs
is. So:
if (connectiontype = 'red') { ...
// is equivalent to (as far as the "if" is concerned):
if ('red') { ...
由于'red'
(非空字符串)在JavaScript中是truthy, if
始终为true,您的 html
变量将始终设置为'Red'
。
Since 'red'
(a non-empty string) is "truthy" in JavaScript, the if
is always true and your html
variable will always be set to 'Red'
.
这篇关于如果情况总是如此,但可能是假的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!