我正在建立一个网页来记录我正在玩的游戏的得分。我有一个名为recordScores的函数,该函数应该在用户单击特定按钮时运行。发生的事情是我必须单击两次按钮才能触发事件和功能。该功能本身正常工作
我最初使用onclick =“ recordScores()”设置了html,但结果相同。由于我在这里发现的建议,我将其更改为使用事件处理程序。
HTML :(在开头<前添加了空格,因此代码可以正确显示)
Enter Score:< input type="text" id="scoreInputBox">
<button id="submitScore">Submit< /button>
Javascript:
// Event Handler
document.getElementById("submitScore").addEventListener("click",
recordScore);
Function:
// Allows the user to enter in a score
function recordScore(){
// First get the value of the person selected from the dropdown
var userDropdown = document.getElementById('playerNameDropdown');
// Get the userId, which is the index value used in the scores array
var userId = userDropdown.options[userDropdown.selectedIndex].value;
// Get the user entered score
var userScore = document.getElementById('scoreInputBox').value;
var score = parseInt(userScore);
// Record the score in the array
scoreArray[userId][round] = score;
if (turnCounter == numPlayers) {
round++;
turnCounter = 1;
score = 0;
addTableRow();
addNewScoreArrayValues();
} else {
turnCounter++;
score = 0;
}
// For testing. Remove when it displays in the browser
// displayArray();
displayScores();
displayTotalScores();
}
预期结果是用户第一次单击“提交”按钮,触发事件处理程序并运行recordScore()函数。
答案 0 :(得分:0)
由于您的按钮类型未提交,因此可能会出现此问题。尝试这个。
<button type='submit' id="submitScore">Submit </button>