-2
我是一名11年級的學生,需要我的老師指定的forloop作業幫助。Forloops作業
代碼的問題在於輸出帖子,但它在消失前僅出現幾毫秒。
function loops1() {
var inputV = document.getElementById('input1').value;
var inputINT = parseInt(inputV);
var show = "";
try {
if (inputV == "") throw "is empty";
if (isNaN(inputV)) throw 'must be a number';
} catch (err) {
alert("Input field " + err);
return;
}
for (var i = 1; i <= inputINT; i++) {
show += i + '<br>';
}
document.getElementById('showN').innerHTML = 'Numbers in order from 1 to n:' + '<br>' + show;
}
function loops2() {
var inputV = document.getElementById('input2').value;
var inputINT = parseInt(inputV);
var sum = 0;
try {
if (inputV == "") throw "is empty";
if (isNaN(inputV)) throw 'must be a number';
} catch (err) {
alert("Input field " + err);
return;
}
for (var i = 1; i <= inputINT; i++) {
sum += i;
}
document.getElementById('showN').innerHTML = 'Sum of numbers from 1 to n:' + '<br>' + sum;
}
function loops3() {
var inputV = document.getElementById('input3').value;
var inputINT = parseInt(inputV);
var sumE = 0;
try {
if (inputV == "") throw "is empty";
if (isNaN(inputV)) throw 'must be a number';
} catch (err) {
alert("Input field " + err);
return;
}
for (var i = 1; i <= inputINT; i++) {
if ((i % 2) == 0) sumE += i;
}
document.getElementById('showN').innerHTML = 'Sum of even numbers from 1 to n:' + '<br>' + sumE;
}
function loops4() {
var inputV = document.getElementById('input4').value;
var inputINT = parseInt(inputV);
var factorial = 1;
try {
if (inputV == "") throw "is empty";
if (isNaN(inputV)) throw 'must be a number';
} catch (err) {
alert("Input field " + err);
return;
}
for (var i = 1; i <= inputINT; i++) {
factorial = factorial * i;
}
document.getElementById('showN').innerHTML = 'Factorial of n:' + '<br>' + factorial;
}
function loops5() {
var sports = ["Cricket", "Volleyball", "Basketball", "Hockey", "Soccer", "Football"];
var sportsD = "";
var lenA = sports.length
for (var i = 0; i < lenA; i++) {
sportsD += sports[i] + '<br>';
}
document.getElementById('showN').innerHTML = 'List of Sports:' + '<br>' + sportsD;
}
<h1>LOOPS</h1>
<form>
Write all numbers between 0 and input<br>
<input type='text' id='input1' placeholder='enter number'><br>
<button onclick='loops1()' type='submit'>Submit</button><br><br> Write sum of numbers 1 to input<br>
<input type='text' id='input2' placeholder='enter number'><br>
<button onclick='loops2()' type='submit'>Submit</button><br><br> Write sum of even numbers from 1 to input<br>
<input type='text' id='input3' placeholder='enter number'><br>
<button type='submit' onclick='loops3()'>Submit</button><br><br> Write factorial of input<br>
<input type='text' id='input4' placeholder='enter number'><br>
<button type='submit' onclick='loops4()'>Submit</button><br><br>
<button type='button' onclick='loops5()'>Display Array</button>
</form>
<div id='showN'></div>
當您單擊表單中的按鈕時,表單將提交併刷新頁面。 – 2017-04-24 16:57:19
具體來說,'type =「submit」'一個(或者沒有'type',因爲'submit'是默認的)。你的'type =「按鈕」'不會。 –
嘗試'onclick ='loops1(); return false;'' – Aakash