【问题标题】:Problems with simple radio button and JavaScript quiz简单单选按钮和 JavaScript 测验的问题
【发布时间】:2021-01-24 02:17:38
【问题描述】:

以下简单测验对我来说没有按预期工作。当我检查单选按钮时,跨度文本不会发生文本颜色更改。

我不确定我的代码的问题出在哪里。我很擅长 HTML 和 CSS,但我仍在提高我的 JavaScript 技能。

提前感谢您的帮助。

Example quiz on CodePen

<input type="radio" name="form[quiz]" value="correct" id="quiz0" class="rsform-radio"><label for="quiz0">Sight</label><span>Correct</span><br>
<input type="radio" name="form[quiz]" value="incorrect" id="quiz1" class="rsform-radio"><label for="quiz1">Smell</label><span>Incorrect</span><br>
<input type="radio" name="form[quiz]" value="incorrect" id="quiz2" class="rsform-radio"><label for="quiz2">Hearing</label><span>Incorrect</span><br>
<input type="radio" name="form[quiz]" value="incorrect" id="quiz3" class="rsform-radio"><label for="quiz3">Taste</label><span>Incorrect</span>

var radioNames = document.getElementsByName("form[quiz]");
for (var i = 0; i < radioNames.length; i++) {
    var radiosValue = radioNames[i];
    if (radiosValue.checked) {
        if (radiosValue.value == "correct") {
            radiosValue.nextSibling.style.color = "green";
        } else {
            radiosValue.nextSibling.style.color = "red";
        }
    } else {
        radiosValue.nextSibling.style.color = "";
    }
}

【问题讨论】:

    标签: javascript html forms radio-button


    【解决方案1】:

    它会为你工作!

    var radioNames = document.getElementsByName("form[quiz]");
    
    radioNames.forEach(radio => {
        radio.addEventListener('change', () => {
            for (var i = 0; i < radioNames.length; i++) {
                var radiosValue = radioNames[i];
                if (radiosValue.checked) {
                    if (radiosValue.value == "correct") {
                        radiosValue.nextSibling.style.color = "green";
                    } else {
                        radiosValue.nextSibling.style.color = "red";
                    }
                } else {
                    radiosValue.nextSibling.style.color = "";
                }
            }
        });
    });
    

    【讨论】:

      【解决方案2】:

      使用&lt;input type="button" /&gt; 添加一个按钮并设置其onClick 事件以运行javascript 函数,在此之前将javascript 代码作为函数包含在&lt;head&gt; 中的&lt;script&gt; 标记之间。

      【讨论】:

      • 我不想为点击事件使用按钮。检查单选按钮应该足以向用户显示他们选择了正确还是错误的答案。
      猜你喜欢
      • 2012-09-19
      • 2017-09-07
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多