Javascript - 整数不能正确加起来,而是追加

时间:2016-10-06 14:34:14

标签: javascript local-storage

我第一次学习JavaScript并且正在进行测验,我试图计算每个学生在进行测验时的尝试次数(他们输入他们的学生ID) form)每个学生最多尝试3次,我试图将这些信息存储在" localStorage.attempts"

在下面的函数中,我有一个if语句,用于检查变量"尝试" (如果分配0或" localStorage.attempts"的值)小于或等于3,并且刚输入的ID与存储中保存的ID匹配。如果满足这些条件,"尝试"增加1.这适用于之前从未使用的ID,"尝试"从0到1.当再次输入相同的ID时,我希望将1添加到1,因此等于2,但不是,显着地添加整数,如下所示:11。代码认为用户有11次尝试他们只是第二次。我已经在任何地方添加了警报来跟踪发生了什么。我无法判断这是否是某种错误,或者我是否需要睡觉。

function numberOfAttempts()
  var errMsg = "";
  var attempts;

  alert("1:" + attempts + localStorage.attempts);

  if (localStorage.attempts == undefined) {
    attempts = 0;
    alert("2: localstorage is undefined" + attempts + localStorage.attempts);
}
  else {
    attempts = localStorage.attempts;
    alert("attempts is assigned to localStorage.attempts" + "  " + attempts + localStorage.attempts);
}

  alert("3: " + attempts + "  " + localStorage.studentID + "  " + document.getElementById("studentID").value);

  if (attempts <= 3 && document.getElementById("studentID").value == localStorage.studentID) {
    attempts = attempts + 1;
    alert("4: incrementing attempts" + "  " + attempts + "  " + localStorage.attempts);
}

  alert("5: " + attempts + localStorage.attempts);

  if (document.getElementById("studentID").value != localStorage.studentID) {
    attempts = 0;
    alert("6: reseting attempts" + attempts + localStorage.attempts);
}

  localStorage.attempts = attempts;

}

0 个答案:

没有答案