2015-01-02 88 views
-1

我想解決這個使用純JavaScript(無jQuery的)顯示使用onClick事件

我寫了解決上項目歐拉的第一個問題的函數的函數的結果。我想創建一個按鈕,用於檢索輸入字段中放置的值,運行該函數,然後在單擊後將結果顯示在單獨的div中。

function problem1() { 
 
    var sum = 0; 
 

 
    for (var i = 0; i < sum; i++){ 
 

 
    if((i % 3 === 0) || (i % 5 === 0)){ 
 
     sum += i; 
 
    }; 
 
}
<div class = "problem1"> 
 
     <h4>Problem 1: Multiples of 3 and 5</h4> 
 
     <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> 
 
     <p>Find the sum of all the multiples of 3 or 5 below <b>1000.</b></p> 
 

 
     <input id = "input" type = "text" value ="1000"></input> 
 
     <button onclick = "getElementById('input').innerHTML=showResult()">Solve</button> 
 
     <div id = "result"></div> 
 
</div>

這裏是展示一下我的工作一的jsfiddle:http://jsfiddle.net/wh9uj2j6/1/

回答

0
function problem1() { 
    var sum = 0; 

    for (var i = 0; i < sum; i++){ //This loop will never run since sum == 0 

    if((i % 3 === 0) || (i % 5 === 0)){ 
     sum += i; 
    }; 
    //nothing is returned. 
} 

其他問題:showResult()不是一個函數,getElementById('input').innerHTML應該是getElementById('input').value

我想你想什麼做的是:

function problem1(num) { 
 
    var sum = 0; 
 

 
    for (var i = 0; i < num; i++) 
 
    { 
 
     if((i % 3 === 0) || (i % 5 === 0)) 
 
     { 
 
      sum += i; 
 
     } 
 
    } 
 
    return sum; 
 
}
<div class = "problem1"> 
 
     <h4>Problem 1: Multiples of 3 and 5</h4> 
 
     <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> 
 
     <p>Find the sum of all the multiples of 3 or 5 below <b>1000.</b></p> 
 

 
     <input id = "input" type = "text" value ="1000"></input> 
 
     <button onclick = "getElementById('input').value=problem1(getElementById('input').value)">Solve</button> 
 
     <div id = "result"></div> 
 
</div>

+0

正是我一直在尋找。謝謝! –

+0

爲什麼downvote,但? – Shahar

0

你的整個javascript函數是沒有意義的,試試這個:

function solve() { 

    var sum = 0; // result var 
    var input = document.getElementById('input').value; // input for iteration 
    for(var i = 0; i < input; i++) { 
     if((i % 3 === 0) || (i % 5 === 0)) { 
      sum += i; 
     } 
    } 

    document.getElementById('result').innerHTML = sum; // print result in div 
}