2017-11-06 13 views
-1

사용자가 값을 입력하고 계산을 계산할 때 함수의 적절한 제수를 계산하려고합니다. HTML 측에 결과를 표시 할 수 있지만 함수는 적절한 약수를 계산하지 않고 대신 "sum"값만 가져옵니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?클라이언트 쪽 Javascript 단추가 작동하지 않습니까?

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(); 
 

 
}
<!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>

+0

계산 코드를 sumOfProperDivisors() 메소드로 옮깁니다. –

답변

2

함수 sumOfProperDivisors() 같은 것을해야 모두에서-작동하지 않습니다 .

+0

정말 고마워요! –

2

sumOfProperDivisors() 기능 아래처럼 내부에 calcultaion 논리를 이동 : -

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>

참고 : -을 합계를 caluculating 당신의 알고리즘으로 외부 기능이기 때문에, 전혀

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

을 작동하지 않습니다

: 논리 함수의 외부에 있기 때문에 그래서 실제로는

1

페이지를로드 할 때 합계를 계산하는 코드가 모든 함수 밖에 있기 때문에 텍스트 상자에는 값이없고 합계가 계산됩니다. 따라서 코드를 넣는 것이 좋습니다. function sumOfProperDivisors를 사용하여 클릭 할 때마다 텍스트 상자에서 값을 가져 와서 합계를 계산합니다.