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

hew*_*own 1 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();">
Run Code Online (Sandbox Code Playgroud)

这是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);
}
Run Code Online (Sandbox Code Playgroud)

Nul*_*ion 8

您正在使用=(赋值)而不是==(比较).

if (connectiontype == 'red') {
    ...
} else if (connectiontype == 'green') {
    ...
}
Run Code Online (Sandbox Code Playgroud)

当你有一个作业时,例如:lhs = rhs整个表达式返回任何东西rhs.所以:

if (connectiontype = 'red') { ...

// is equivalent to (as far as the "if" is concerned):

if ('red') { ...  
Run Code Online (Sandbox Code Playgroud)

由于'red'(非空字符串)在JavaScript中是"真实的",因此if始终为true,并且您的html变量将始终设置为'Red'.

  • 比较相等与非空字符串时不需要使用=== (2认同)