javascript - 如果大小写始终为真,但可能为假

标签 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);
}

最佳答案

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

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/

相关文章:

javascript - 使用 Angular,我如何在 ng-show 中调用自定义过滤器的结果?

Javascript:如何更改 contenteditable div 占位符颜色

javascript - 制作一个html+css页面独立静态

javascript - 元素在搜索后渲染 ReactJS

javascript - 函数触发时如何更新我的 DOM?

javascript - 在 WebView 中加载 HTML 文件后执行 JavaScript 指令

Javascript 函数不会使用 Cookie 执行

javascript - 无法使用 Sequelize 更新(或保存)现有行

javascript - 我可以遍历 for 循环来创建更多的 javascript 吗?

javascript - Express.js 或 React.js 中的通用用户名/密码身份验证