【发布时间】:2019-08-08 00:48:06
【问题描述】:
我正在构建一个网页来记录我正在玩的游戏的分数。我有一个名为 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()函数运行。
【问题讨论】:
-
提供全部代码
标签: javascript button click