我有一个简单的表单下拉列表,我想根据选择值显示不同的内容。我有一个名为 connectiontype 的变量,它带有下拉列表中的正确值,但 if/else 语句似乎不起作用 - 我总是以红色结束。关于原因有什么想法吗?
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。
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);
}
最佳答案
您正在使用 =
(赋值)而不是 ==
(比较)。
if (connectiontype == 'red') {
...
} else if (connectiontype == 'green') {
...
}
当你有一个赋值时,例如:lhs = rhs
整个表达式返回 rhs
是什么。所以:
if (connectiontype = 'red') { ...
// is equivalent to (as far as the "if" is concerned):
if ('red') { ...
由于 'red'
(非空字符串)在 JavaScript 中是“真实的”,if
始终为真并且您的 html
变量将始终设置为 'Red'
。
关于javascript - 如果大小写始终为真,但可能为假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8156112/