【问题标题】:Same boolean result is displayed no matter the input无论输入如何,都会显示相同的布尔结果
【发布时间】:2020-06-06 23:23:16
【问题描述】:

我正在尝试编写一个简单的脚本,其中有两组单选按钮,具有 True 和 False 值。这个想法是,如果两个 True 按钮都被选中,则显示“true”,如果选择的按钮之一是 False,则显示“false”。不管输入如何,结果总是显示为“true”。

    <p>Select "True" or "False"</p>
    <form>
        <input type="radio" id="true1" name="bool1" value=true><br>
        <label for="true1">True</label><br>
        <input type="radio" id="false1" name="bool1" value=false><br>
        <label for="false1">False</label><br>
    </form>
    <p>Select "True" or "False" again</p>
    <form>
        <input type="radio" id="true2" name="bool2" value=true><br>
        <label for="true2">True</label><br>
        <input type="radio" id="false2" name="bool2" value=false><br>
        <label for="false2">False</label><br>
    </form>
    <input type="button" onclick="and()" value="Submit">
    <p id="and"></p>

<script>
    var radio1;
    var radio2;
    var result;
    function and(){
        try {
            radio1 = document.querySelector('input[name="bool1"]:checked').value;
            radio2 = document.querySelector('input[name="bool2"]:checked').value;
            if (radio1 && radio2)
            {
                document.getElementById("and").innerHTML = "True";
            }
            else
            {
                document.getElementById("and").innerHTML = "False";
            }
        }
        catch {
            alert("Select a checkbox on each form");
        }
    }
</script>

我在这里束手无策。我什至确保通过 if 语句显示 radio1 和 radio2 的值,果然,当 radio1 或 radio2 的值为 false 时,它​​仍然会显示“True”。这怎么可能?

【问题讨论】:

  • 如果两者都是假的,你想要假吗?

标签: javascript html boolean-operations


【解决方案1】:

单选按钮的值不是布尔值,它们是字符串,非空字符串在 JavaScript 中的计算结果为 true。它们被认为是truthy 值。

您可以使用严格的比较:

radio = document.querySelector('input[name="bool1"]:checked').value;

if (radio === 'True') { /* ... */ } else { /* ... */ }

【讨论】:

  • 哦,谢谢。我完全忘记了 HTML 中不存在布尔值,哈哈。
【解决方案2】:

罗比在我整理答案时回答。所以是的,你给了变量字符串值,你的 if 需要比较多个条件:

var radio1;
 var radio2;
 var result;

 function and() {
   try {
     radio1 = document.querySelector('input[name="bool1"]:checked').value;
     radio2 = document.querySelector('input[name="bool2"]:checked').value;
     if ((radio1 == "true") && (radio2 == "true")) {
       document.getElementById("and").innerHTML = "True";
     } else {
       document.getElementById("and").innerHTML = "False";
     }
   } catch (err) {
     alert("Select a checkbox on each form");
   }
 }

jsFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多