2017-02-22 356 views
0

這是我的代碼的Javascript輸出不正確

var form = document.getElementById("addStudent"); 
 

 
form.addEventListener("submit", function(event) { 
 
    // Get form items 
 
    var jerseyNumber = document.getElementById("jerseyNumber").value; 
 
    var completions = document.getElementById("completions").value; 
 
    var attempts = document.getElementById("attempts").value; 
 
    var player = new Object(); 
 
    player.attempts = attempts; 
 
    player.completions = completions; 
 
    player.jerseyNumber = jerseyNumber; 
 

 
    function percentage() { 
 
    var e = ((player.completions/player.attempts) * 100); 
 
    return e; 
 
    } 
 

 
    function showResults(event) { 
 
    document.getElementById("results").innerHTML = "Freethrow Percentage for # " + player.jerseyNumber + " is " + percentage.e + "%"; 
 
    } 
 
    showResults(); 
 
    resetForm(jerseyNumber, completions, attempts); 
 
    event.preventDefault(); // Stop the form from submitting 
 
}, false); 
 

 
// Resets the form after it's submitted 
 
function resetForm(jerseyNumber, freethrowCompleted, freethrowAttempts) { 
 
    jerseyNumber.value = ""; 
 
    freethrowCompleted.value = ""; 
 
    freethrowAttempts.value = ""; 
 
}

和輸出 「爲#23 Freethrow百分比是未定義%」

,基本上我不知道爲什麼e返回爲undefined

而這正是我嘗試做

  1. 提交表單後,你的程序必須創建一個JavaScript對象來代表玩家。對象必須具有屬性以包含球衣號碼,他們的投籃嘗試和射門完成。對象還必須包含計算球員罰球命中率的方法。下面是公式:Math.round(completed/attempts * 100)
  2. 然後,您必須創建一個名爲showResults()的函數,將此學生對象作爲參數,並在屏幕上以id =「結果顯示div的結果」。以下示例使用此HTML:<h4>Freethrow Percentage for #23: 94%</h4>。射擊百分比必須用百分號四捨五入到最接近的整數(請參閱上面的公式和下面的截圖)。
+1

你寫出'percentage.e',但有沒有分配給這個值。 * e *是一個變量,而不是對象屬性。變量不可用作函數的屬性,你需要'... + percentage()+ ...'。 – RobG

+1

要調用一個函數,在其後加上括號,'percentage()'。 – Barmar

回答

0

您應該做percentage(),調用您的百分比方法,而不是試圖引用屬性的百分比e屬性。

+0

功能之後沒有'.e'。 – Barmar

+0

Doh!謝謝:)忽視 –

0
document.getElementById("results").innerHTML = "Freethrow Percentage for # " + player.jerseyNumber + " is " + percentage.e + "%"; 

應該是:

document.getElementById("results").innerHTML = "Freethrow Percentage for # " + player.jerseyNumber + " is " + percentage() + "%"; 

percentage是一個函數的名稱,而不是一個對象。要調用一個函數,你需要在後面加括號。 e是它返回的局部變量的名稱,而不是屬性。

0

我認爲這是因爲你的函數不是你的對象的一部分。嘗試在這樣的對象中包含percentage函數。

var player = new Object(); 
player.attempts = attempts; 
player.completions = completions; 
player.percentage = function() { 
    var e = ((player.completions/player.attempts * 100); 
    return e; 
} 

然後你可以調用該函數的字符串中有player.percentage()

0

更換
document.getElementById("results").innerHTML = "Freethrow Percentage for # "+player.jerseyNumber+" is "+percentage.e+"%";
有了:

document.getElementById("results").innerHTML = "Freethrow Percentage for # "+player.jerseyNumber+" is "+percentage()+"%";