mca*_*ams 4 javascript console logging if-statement
我有以下来自现代 Javascript 练习的简单代码,用于计算球体的体积,它包含一个检查以确保已输入半径值的部分。
我输入一个负数来测试该功能,它可以工作,但我对控制台中显示的内容感兴趣,所以我检查了。我最终在日志中看到错误闪烁,然后消失 - 速度太快,无法阅读。
这就是 if 语句计算结果为 false 时发生的情况吗?为什么会显示此错误,然后几乎立即被清除?我知道我可以使用另一种方法来调试这个问题(又名使用 console.log 或通过其他方式记录问题),我只是感兴趣为什么这个错误消失。
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Volume of a Sphere Calculator</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- sphere.html -->
<form action="" method="post" id="theForm">
<fieldset>
<p>Use this form to calculate the volume of a sphere.</p>
<div>
<label for="radius">Radius</label>
<input type="text" name="radius" id="radius" required></div>
<div>
<label for="volume">Volume</label>
<input type="text" name="volume" id="volume"></div>
<div>
<input type="submit" value="Calculate" id="submit"></div>
</fieldset>
</form>
<script src="js/sphere.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
JS:
function calculate() {
'use strict';
var volume;
var radius = document.getElementById('radius');
if (radius && (radius.value > 0)){
volume = (4/3) * Math.PI * Math.pow(radius.value, 3);
}
volume = volume.toFixed(4);
document.getElementById('volume').value = volume;
return false;
}
function init() {
'use strict';
var theForm = document.getElementById('theForm');
theForm.onsubmit = calculate;
}
window.onload = init;
Run Code Online (Sandbox Code Playgroud)
因为这是针对我的 console.log 输出出现和快速消失问题的顶级 Google 匹配,所以这种情况发生在我身上,因为我要么有一组空的标签标签不合适,要么有一个没有任何操作的表单。删除这些标签会导致 JavaScript 和 console.log() 像预期的那样工作。
| 归档时间: |
|
| 查看次数: |
13202 次 |
| 最近记录: |