客户端Javascript按钮不起作用?

时间:2017-11-06 08:58:47

标签: javascript jquery html client client-side

当用户输入一个值并命中计算时,我试图计算一个函数的正确除数。我能够将结果显示在HTML端,但是该函数不会计算正确的除数,而是采用" sum"的值。只要。我做错了什么?



function sumOfProperDivisors() {
  return sum;
}

var input = document.getElementById("input").value;
var sum = 0;

{
  for (i = 1; i <= input; i++)
    if (input % i == 0)
      sum = sum + i;
}

function display() {

  document.querySelector("div").innerHTML = "<b> Sum = " + sumOfProperDivisors();

}
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Sum of Prop. Div.</title>
  <h2> Sum of Proper Divisors </h2>
</head>

<body style="background-color:teal;">

  <p> Enter a Positive Integer (N): </p>
  <input type="number" id="input">

  <p><button onclick="display()">Calculate the Sum of Divisors</button></p>

  <div></div>

  <script src="sumOfPDivs.js"></script>

</body>

</html>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

将您的calcultaion逻辑移到sumOfProperDivisors()函数中,如下所示: -

function sumOfProperDivisors() {
  var input = document.getElementById("input").value;
  var sum = 0;
  for (i=1; i<=input; i++){
    if (input%i==0){
      sum = sum + i;
    }
  }
  return sum;
}

function display(){
  document.querySelector("div").innerHTML = "<b> Sum = " + sumOfProperDivisors();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sum of Prop. Div.</title>
<h2> Sum of Proper Divisors </h2>
</head>
<body style="background-color:teal;">

<p> Enter a Positive Integer (N): </p>
<input type="number" id="input">

<p><button onclick="display()">Calculate the Sum of Divisors</button></p>

<div></div>

<script src="sumOfPDivs.js"></script>

</body>
</html>

注意: - ,因为逻辑在函数之外,所以实际上它根本不能正常工作

答案 1 :(得分:2)

你的函数sumOfProperDivisors()应该是这样的:

    function sumOfProperDivisors(){
     var input = document.getElementById("input").value;
     var sum = 0;
     {
        for (i=1; i<=input; i++)
        if (input%i==0)
        sum = sum + i;
        return sum; 
    }

由于你计算总和的算法不在函数范围内,它根本不起作用。

答案 2 :(得分:1)

当您的页面被加载时,您的文本框将没有值,并且将在页面加载时计算总和,因为计算总和的代码在任何函数之外,因此最好将代码放在函数中sumOfProperDivisors,以便它在每次点击时从文本框中获取值,然后计算总和。