首页 > 解决方案 > 为什么函数 javascript 给我相同的值

问题描述

为什么当我希望每次选择其他单选按钮时函数都给我相同的值

    <form>
    <input type="radio" id="male" name="gender" value="male">
    <label for="male">Male</label><br>
    <input type="radio" id="female" name="gender" value="female">
    <label for="female">Female</label><br>
    <input type="radio" id="other" name="gender" value="other">
    <label for="other">Other</label>
    <button onclick="addSpan()">Try it</button>

</form>

这是功能

<script>
function addSpan() {
    var female = document.getElementById("female");
    var male = document.getElementById("male");
    var other = document.getElementById("other");
    if (document.getElementById("female").checked = true) {
        document.body.innerHTML += '<span class="bullet">female</span> ';
    }
    else if (document.getElementById("male").checked = true) {
        document.body.innerHTML += '<span class="bullet">male</span> ';
    }
    else {
        document.body.innerHTML += '<span class="bullet">other</span> ';
    }
}
resultat [在此处输入图像描述][1]

标签: javascripthtml

解决方案


用于=代替===

function addSpan() {
    var female = document.getElementById("female");
    var male = document.getElementById("male");
    var other = document.getElementById("other");
    if (female.checked === true) { // when checking something is true/false use === not = as = assigns a new value and === is checking if it is equal, also use the variables you assigned at the start
        document.body.innerHTML += '<span class="bullet">female</span> ';
    }
    else if (male.checked) { // You can actually shorthand this as an IF statement automatically checks for if its equal to true
        document.body.innerHTML += '<span class="bullet">male</span> ';
    }
    else {
        document.body.innerHTML += '<span class="bullet">other</span> ';
    }
}

推荐阅读