javascript - Parsint 查询始终显示为 NaN
问题描述
使用下面的代码,我得到“你的分数是 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() 只有在检查时才会获得带有 name='benefit1' 的输入元素,但是当没有选中的复选框。所以这个 $("input[name='benefit1']:checked") 查询不会检索任何元素。我的建议是在每个复选框元素上附加 onclick 事件并调用处理事件的函数。像这样:<input type="checkbox" name="benefit1" value="1" onclick="handleCheckbox(this)"/>
handleCheckbox 函数:
function handleCheckbox(checkbox){
result = parseInt(this.value);
...
}
推荐阅读
- python - Python webscraping with beautifulsoup
- python - 使用 Django 在 JWT 中导致有效负载错误的问题是什么
- visual-studio-code - 使用 VSCode 在 azure 区块链服务上部署合约时如何解决 HttpService.sendRPCRequest ECONNREFUSED 错误?
- php - PHP解压溢出变量内存限制
- javascript - 将 javascript 中创建的对象输出到服务器端 JSON 文件
- javascript - 实例化子类而不构造
- python - 是否可以单行执行此循环?
- angular - 将字符串类型转换为组件
- phpmyadmin - 如何将 phpMyAdmin 配置为从 SQL 选项卡中以空白 sql 查询开始?
- python - 从 Google 新闻中获取给定时间范围内的结果数量