这是我的代码
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
的形式返回。
这就是我想要做的事情
<h4>Freethrow Percentage for #23: 94%</h4>
。拍摄百分比必须四舍五入到最接近的整数(参见上面的公式和下面的屏幕截图),并带有百分号。答案 0 :(得分:0)
您应该执行percentage()
,调用百分比方法,而不是尝试在百分比对象上引用属性e
。
答案 1 :(得分: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
是它返回的局部变量的名称,而不是属性。
答案 2 :(得分: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()
答案 3 :(得分:0)
替换
document.getElementById("results").innerHTML = "Freethrow Percentage for # "+player.jerseyNumber+" is "+percentage.e+"%";
随着:
document.getElementById("results").innerHTML = "Freethrow Percentage for # "+player.jerseyNumber+" is "+percentage()+"%";