【问题标题】:I have to click a button twice for an event handler to fire javascript我必须单击一个按钮两次才能让事件处理程序触发 javascript
【发布时间】: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


【解决方案1】:

当您的按钮类型不是提交时,可能会出现此问题。试试这个。

 <button type='submit' id="submitScore">Submit </button>

【讨论】:

  • 不走运。我用相同的结果更新了我的 html。不过,谢谢你发现我的一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 2020-06-29
相关资源
最近更新 更多