2017-09-23 70 views
1

我有兩個輸入字段和一個按鈕。當用戶點擊按鈕時,我希望它顯示用戶在第一次輸入中寫入的文本,即用戶在第二次輸入中寫入的次數。嘗試打印輸出文本用戶使用while循環在secound輸入中寫入的次數

我知道你必須爲此使用while循環。我在這裏做錯了什麼?

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <title>While Loop</title> 
 
    <script type="text/javascript"> 
 
    window.onload = btn; 
 

 
    function btn() { 
 
     document.getElementById("btn").onclick = showText; 
 
    } 
 

 
    function showText() { 
 
     var text = ""; 
 
     var inputOne = document.getElementById("txtBox").value; 
 
     var inputTwo = document.getElementById("numBox").value; 
 
     while (inputOne < inputTwo) { 
 
     text += inputOne; 
 
     inputOne++; 
 
     } 
 
     document.getElementById("showCode").innerHTML = text; 
 
    } 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <input type="text" id="txtBox"><br/> 
 
    <input type="number" id="numBox"><br/> 
 
    <button type="button" id="btn">Click Me!</button> 
 
    <p id="showCode"></p> 
 
</body> 
 

 
</html>

回答

0

由於inputOne是一個文本,你不能增加它(你不能做inputOne++),而是使用另一個變量,我們稱之爲i,控制while循環:

window.onload = btn; 
 

 
function btn() { 
 
    document.getElementById("btn").onclick = showText; 
 
} 
 

 
function showText() { 
 
    var text = ""; 
 
    var inputOne = document.getElementById("txtBox").value; 
 
    var inputTwo = document.getElementById("numBox").value; 
 
    var i=1; // to control the loop 
 
    while (i <= inputTwo) { // i goes from 1 to inputTwo 
 
    text += inputOne; 
 
    i++; 
 
    } 
 
    document.getElementById("showCode").innerHTML = text; 
 
}
<input type="text" id="txtBox"><br/> 
 
<input type="number" id="numBox"><br/> 
 
<button type="button" id="btn">Click Me!</button> 
 
<p id="showCode"></p>

+0

這是完美的!多謝你們。 –

0

這是我的解決方案

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <title>While Loop</title> 
 
    <script type="text/javascript"> 
 

 
    window.onload = btn; 
 

 
    var count = 0; 
 

 
    function btn() { 
 
     document.getElementById("btn").onclick = showText; 
 
    } 
 

 
    function showText() { 
 

 
     var text = ""; 
 
     console.log("Text: "+text); 
 

 
     var inputOne = document.getElementById("txtBox").value; 
 
     console.log("Input One: "+inputOne); 
 

 
     var inputTwo = document.getElementById("numBox").value; 
 
     console.log("Input 2: "+inputTwo); 
 

 
     count=count+1; 
 
     console.log("Times: "+count); 
 

 
     document.getElementById("numBox").value = count; 
 

 
     document.getElementById("showCode").innerHTML = text; 
 
    } 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <input type="text" id="txtBox"><br/> 
 
    <input type="number" id="numBox"><br/> 
 
    <button type="button" id="btn">Click Me!</button> 
 
    <p id="showCode"></p> 
 
</body> 
 

 
</html>

0

相反,while循環,你可以使用一個像這樣的循環:

for(let i = inputTwo; i>0; i--) { 
    text += inputOne; 
}