方形javascript程序的区域

时间:2014-10-30 21:33:57

标签: javascript html area

以下是代码:

<h2>Area of a Square (A = s<sup>2</sup>)</h2>
    <form>
    <label class = "left">Side Length: </label>  <input id = "areaSquare" type = "text" class = "right" /> <br />
    <label class = "left">Answer: </label>  <input id = "answerAreaSquare" type = "text" class = "right" /> <br />
    <input type = "submit" value = "Submit" onclick = "areaSquare(); return false" />
    </form>

function areaSquare(side)
{
side = document.getElementById("areaSquare").value;
var answer = side*side;
document.getElementById("answerAreaSquare").value = answer;
}

我认为这是一个非常简单的程序,但我不知道为什么这不起作用。请帮忙。

1 个答案:

答案 0 :(得分:0)

您正尝试从onclick属性调用全局函数。浏览器对内部事件属性(如onclick)的范围做了很多奇怪的事情,当在表单控件中使用时,会有局部变量通过其id引用所有表单控件。

由于您的id具有与全局函数匹配的元素,因此它在本地范围内获取变量并屏蔽该函数。

你可以用以下方法测试:

 onclick="alert(areaSquare); areaSquare(); return false" 

快速而肮脏的黑客就是重命名其中一个。


更好的解决方案是首先避免使用全局

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Demo</title>
</head>
<body>
<h1>Area of a Square (A = s<sup>2</sup>)</h1>
    <form>
      <label for="areaSquare">Side Length: </label>
      <input id="areaSquare"> <br>

      <label for="answerAreaSquare">Answer: </label>
      <output id="answerAreaSquare"></output> <br>

      <input type="submit" value="Submit">
    </form>
<script>
// IIFE for scope
(function () {

  // Locally scoped function
  function areaSquare(event) {
    var side = document.getElementById("areaSquare").value;
    var answer = side*side;
    document.getElementById("answerAreaSquare").value = answer;
    event.preventDefault();
  }

  // Event handler bound with JS instead of HTML
  document.querySelector('form').addEventListener('submit', areaSquare);
})();
  </script>

</body>
</html>