2017-04-15 109 views
1

我是jessi,我是一名網絡開發學生。我正在嘗試編寫一個程序與數組,我卡住了。我有一組短語,當用戶輸入一個介於1到10之間的數字時,它應該顯示屏幕上有很多短語,但我被卡住了。我不知道如何在屏幕上顯示多個結果。我非常感謝任何幫助。謝謝。javascript數組和循環

<!DOCTYPE html> 
    <html> 
    <head> 
    <title>Get A Response</title> 
    </head> 

<body> 
<form> 
    <h1>Select how many phrases you want displayed.</h1> 
    <input type="number" class="userInput"></input> 
    <button type="submit" value="submit" onclick="showme()"></button> 
</form> 

<div class="myphrases"> 
</div> 

<script src="js/main.js"></script> 

</body> 
</html> 

    ////////////////// Javascript 

function showme() { 
    var number = document.querySelector('.userInput').value; 


    var display = ""; 

    var phrases = [ 
    "Hello there", 
    "What's up Doc", 
    "Because I said so", 
    "Say it again", 
    "It's a celebration", 
    "Enjoy yourselves", 
    "Welcome", 
    "Where did you go", "Why you crying", "Stop playing"]; 


    var random = Math.floor(Math.random() * phrases.length); 

    for(var i = 0; i < phrases.length; i++) { 

    } 
    } 

回答

3

首先,您應該設置一個HTML元素作爲您的輸出區域。一個空的div元素是一個不錯的選擇。你已經完成了:<div class="myphrases"></div>

接下來,HTML input元素沒有得到關閉標籤(</input>)和,而不是使用submit按鈕,只需使用常規的按鈕(因爲你實際上並沒有提交任何位置的數據)。

另外,不要使用內嵌HTML事件處理屬性(的onclick,的onmouseover,等等),因爲它們:

  1. 創建導致重複,使得代碼難以閱讀麪條代碼。
  2. 導致圍繞您的屬性值創建全局匿名包裝函數,並在您的回調函數中更改this綁定。
  3. 請勿遵循使用.addEventListener()的W3C事件標準。

接下來,沒有循環遍歷每個短語(phrases.length)。只有用戶輸入的次數。

// Get reference to the text box, the button and the output area 
 
var number = document.querySelector('.userInput'); 
 
var btn = document.querySelector("button"); 
 
var output = document.querySelector(".myphrases"); 
 

 
// Set up the event handling function for the button 
 
btn.addEventListener("click", showme); 
 

 
function showme() { 
 
    
 
    var display = ""; 
 

 
    var phrases = [ 
 
    "Hello there", 
 
    "What's up Doc", 
 
    "Because I said so", 
 
    "Say it again", 
 
    "It's a celebration", 
 
    "Enjoy yourselves", 
 
    "Welcome", 
 
    "Where did you go", "Why you crying", "Stop playing"]; 
 

 
    // String to hold loop results 
 
    var result = ""; 
 
    
 
    // Set up the upper limit for the loop. 
 
    // If the entered value is greater than the length of the array, use the length 
 
    // of the array. If not, use the value entered by the user 
 
    var count = number.value > phrases.length ? phrases.length : number.value; 
 
    
 
    for(var i = 0; i < count; i++) { 
 
     var random = Math.floor(Math.random() * phrases.length); 
 
     result += phrases[random] + "<br>"; 
 
    } 
 
    
 
    // Inject the string into the output area 
 
    output.innerHTML = result; 
 
    }
<form> 
 
    <h1>Select how many phrases you want displayed.</h1> 
 
    <input type="number" class="userInput"> 
 
    <button type="button">Submit</button> 
 
</form> 
 

 
<div class="myphrases"></div>

最後,您可以通過調整其innerHTML是,你從你的循環建立一個字符串更新div輸出區域