2011-11-16 38 views
1

我有一個簡單的表單下拉列表,我希望根據選擇值顯示不同的內容。我有一個名爲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); 
} 
+0

不應該是'if(connectiontype =='red')'等等...... – talnicolas

回答

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「truthy」,該if始終是真實的,你的html變量將始終設置爲'Red'

+1

一般比較好用'==='來避免類型轉換 –

+2

比較時不需要===與非空字符串相等 – Esailija

+0

我知道這是愚蠢的,謝謝。 – hewhocutsdown