Javascript中的Prompt()方法

时间:2014-08-29 00:01:29

标签: javascript

我是Javascript的初学者,我有一个关于如何使用提示方法的基本问题。这些代码似乎都没有在下面处理。是否存在某种关于使用多个提示框的隐藏规则,或者我的代码是否只有语法错误?任何帮助将非常感激。提前谢谢。

    <html>
    <head> 
    <title> Two Numbers </title>
    <script type="text/javascript">
    var first = prompt("Enter first number:");
    var second = prompt("Enter second number:");

    var sum = (first-0) + (second-0);
    var diff = first - second;
    var divide = first/second;
    var multi = first*second;


    document.write(first + " + " + second " = " + sum + "<br />"); 
    document.write(first + " + " + second " = " + diff + "<br />"); 
    document.write(first + " + " + second " = " + divide + "<br />"); 
    document.write(first + " + " + second " = " + multi + "<br />"); 

    </script>
    </head>

    <body> 
    </body>
    </html>

3 个答案:

答案 0 :(得分:1)

更正了语法错误并更正了write()函数中的运算符:

<html>
<head>
<title> Two Numbers </title>
<script type="text/javascript">
var first = prompt("Enter first number:");
var second = prompt("Enter second number:");

var sum = (first-0) + (second-0);
var diff = first - second;
var divide = first/second;
var multi = first*second;

document.write(first + " + " + second + " = " + sum + "<br />");
document.write(first + " - " + second + " = " + diff + "<br />");
document.write(first + " / " + second + " = " + divide + "<br />");
document.write(first + " * " + second + " = " + multi + "<br />");

</script>
</head>
<body>
</body>
</html>

使用控制台检查错误,如James G所述

答案 1 :(得分:1)

您错过了+

//change this
console.log(first + " + " + second " = " + sum + "<br />"); 
// to this
console.log(first + " + " + second + " = " + sum + "<br />"); 

将来,请使用控制台进行调试。关于你可以在这里使用控制台做的所有事情,有一篇很棒的文章&gt; https://developer.chrome.com/devtools/docs/javascript-debugging

答案 2 :(得分:0)

var isValid = true;

var first = prompt("Enter first number:");
if (!Number(first)) {
  alert("Please enter numeric value only.");
  isValid = false;
}

if (isValid) {
  var second = prompt("Enter second number:");
  if (!Number(second)) {
    alert("Please enter numeric value only.");
    isValid = false;
  }

  if (isValid) {
    var sum = first + second;
    var diff = first - second;
    var divide = first / second;
    var multi = first * second;

    console.log(first + " + " + second + " = " + sum);
    console.log(first + " - " + second + " = " + diff)
    console.log(first + " / " + second + " = " + divide);
    console.log(first + " * " + second + " = " + multi);
  }
}