如果情况总是正确的,但也可能是错误的

If case is always true, but probably false

本文关键字:也可能 错误 情况 如果      更新时间:2023-09-26

我有一个简单的表单下拉列表,我希望根据选择值显示不同的内容。我有一个名为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中是" true ",因此if始终为true,并且您的html变量将始终设置为'Red'

相关文章: