3

我从用于计算球体体积的现代 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>

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;
4

4 回答 4

4

因为这是我的 console.log 输出出现并迅速消失的问题的最佳 Google 匹配项,所以这发生在我身上,因为我要么有一组空的标签标签不合适,要么是一个没有任何操作的表单。删除这些标签会导致 JavaScript 和 console.log() 像预期的那样工作。

于 2015-03-31T15:09:07.417 回答
2

添加另一个解决方案作为谷歌搜索“javascript 日志消失”将我带到这里。

页面刷新/导航是问题所在。

根据 mateuszb 的评论在控制台设置中选择“保留日志”解决了该问题。

于 2020-03-19T09:39:02.810 回答
1

因为undefined没有一个方法toFixed,它会抛出一个错误,阻止Calculate永远到达return false;

由于从未到达该行,因此表单提交,这(一般来说)将表单发布到同一页面。

当页面重新加载时,控制台被重置(我相信这取决于特定的浏览器)。

要解决此问题,请初始化volume0.

于 2013-01-03T23:38:47.330 回答
0

您可以使用 el.preventDefault(); 在你的回调函数中

于 2020-08-05T23:39:47.367 回答