Javascript输出不正确

时间:2017-02-22 20:13:17

标签: 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()的函数,该函数将此学生对象作为参数,并在div中使用id =“results”在屏幕上显示结果。以下示例使用此HTML:<h4>Freethrow Percentage for #23: 94%</h4>。拍摄百分比必须四舍五入到最接近的整数(参见上面的公式和下面的屏幕截图),并带有百分号。

4 个答案:

答案 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()+"%";