如果情况总是如此,但可能是假的

时间:2011-11-16 17:39:48

标签: javascript

我有一个简单的表格下拉菜单,我想根据选择值显示不同的内容。我有一个名为 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);
}

1 个答案:

答案 0 :(得分:8)

您使用的是=(作业),而不是==(比较)。

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始终为true,而您的html变量将始终设置为'Red'

相关问题