我想使用纯JavaScript(No Jquery)来解决这个问题
我编写了一个函数来解决关于Project Euler的第一个问题。我想创建一个按钮,检索输入字段中放置的任何值,运行该函数,然后在单击后将结果显示在单独的div中。
function problem1() {
var sum = 0;
for (var i = 0; i < sum; i++){
if((i % 3 === 0) || (i % 5 === 0)){
sum += i;
};
}
&#13;
<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>
&#13;
这是一个显示我正在使用的内容的jsfiddle:http://jsfiddle.net/wh9uj2j6/1/
答案 0 :(得分:1)
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;
}
&#13;
<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>
&#13;
答案 1 :(得分: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
}