【问题标题】:Parsint Query always showing as NaNParsint 查询始终显示为 NaN
【发布时间】:2020-08-18 10:45:10
【问题描述】:

使用下面的代码,我得到“你的分数是 NaN”,但我不知道为什么。最终代码将把测验中的所有问题加起来。

在浏览器中,我可以看到收音机的值被正确拾取,我使用 parseint 将其转换为数字。但显然有问题

感谢您的帮助。

<form id="form1" method="post">
<br><strong><label for="benefit1">From the list below select those that are ISO27001 Benefits 
</strong></span></label><br><br>
<input type="checkbox" name="benefit1" value="1" /> Helps you to comply with other regulations</p>
<input type="checkbox" name="benefit2" value="1" /> Keeps confidential information secure</p>
<input type="checkbox" name="benefit3" value="1" /> Protects the company, assets, shareholders and 
directors</p>
<input type="checkbox" name="benefit4" value="1" /> Allows for secure exchange of information</p>
<input type="checkbox" name="benefit5" value="1" /> Manages and minimises risk exposure</p>


<br><input id="Q4PrevBut" type="button" Value="Previous Question">  
    <input id="Q4NextBut" type="button" Value="Next Question">  

</form>

</div>

<div class ="Q5">

<p>Your score is: <span id="grade"></span></p>

<script>

var a1 = parseInt($("input[name='benefit1']:checked").val());

var result = a1;
   
document.getElementById("grade").innerHTML = result;

</script>

</div>
</body>
</html>

【问题讨论】:

  • 您的代码立即运行,无需等待用户输入内容。你需要提供一个事件监听器
  • 你还需要考虑如果没有选中复选框,$("input[name='benefit1']:checked").val() 将评估什么。

标签: javascript parseint


【解决方案1】:

您的查询 $("input[name='benefit1']:checked").val() 只有在检查时才会获得 name='benefit1' 的输入元素,但您的脚本会在加载页面时立即执行没有选中的复选框。所以这个 $("input[name='benefit1']:checked") 查询不会检索任何元素。 我的建议是在每个复选框元素上附加 onclick 事件并调用处理事件的函数。 像这样的东西:&lt;input type="checkbox" name="benefit1" value="1" onclick="handleCheckbox(this)"/&gt; 处理复选框功能:

function handleCheckbox(checkbox){
   result = parseInt(this.value);
...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 2017-11-01
    • 2017-06-02
    • 1970-01-01
    相关资源
    最近更新 更多