首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将所有按钮循环到单击事件侦听器

如何将所有按钮循环到单击事件侦听器
EN

Stack Overflow用户
提问于 2021-06-04 16:17:46
回答 3查看 1.5K关注 0票数 0

我正在为一个项目制作一个简单的游戏,并需要每个按钮的对应值在单击时显示在输入中。

我能够在以下JS中成功地使用"getElementById“:

代码语言:javascript
复制
window.addEventListener("load", function() {
const button1 = document.getElementById("button-one");

button1.addEventListener("click", function(e) {
   document.getElementById("user-input").value += button1.value;
   document.getElementById("user-input").focus();
});

当然,我可以对所有按钮0-9重复这段代码,但如果可能的话,我想使用“循环”来完成这一任务,只需一段代码。我做了下面的尝试,只想模仿上面对一个"id“起作用的代码,然后通过"querySelectorAll”和“getElementsByClassName”循环关闭“querySelectorAll”。我得到了一个错误:"button.addEventListener不是一个函数。“我不明白,因为在成功的单按钮代码“button on1.addEventListener(”click“,function(e)”)中,函数(E)也不是一个函数,但它能工作.下面是循环尝试,后面是整个页面:

代码语言:javascript
复制
var buttons = document.querySelectorAll("td>button");
for(var button = 0; button < buttons.length; button++)
{
button.addEventListener("click", function() {
   document.getElementById("user-input").value += button.value;
   document.getElementById("user-input").focus();
});
}
});


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" href="../normalize.css">
<style>
input {
    margin-top: 10px;    
}

table {    
    margin-bottom: 10px;
    width: auto;    
    margin-top: 10px;    
}
</style>
<script>
window.addEventListener("load", function() {
    
 // This works   
const button1 = document.getElementById("button-one");

button1.addEventListener("click", function(e) {
   document.getElementById("user-input").value += button1.value;
   document.getElementById("user-input").focus();
});


//This doesn't work
var buttons = document.querySelectorAll("td>button");
for(var button = 0; button < buttons.length; button++)
{
button.addEventListener("click", function() {
   document.getElementById("user-input").value += button.value;
   document.getElementById("user-input").focus();
});
}
});


</script>
<title>Test</title>
</head>
<body>
   
<main>
    <input  id="user-input">
    <table>
        <tr>
            <td><button type="button" value="1" id="button-one" class="calc">1</button></td>
            <td><button type="button" value="2" class="calc">2</button></td>
            <td><button type="button" value="3" class="calc">3</button></td>
        </tr>
        <tr>
            <td><button type="button" value="4" class="calc">4</button></td>
            <td><button type="button" value="5" class="calc">5</button></td>
            <td><button type="button" value="6" class="calc">6</button></td>
        </tr>
        <tr>
            <td><button type="button" value="7" class="calc">7</button></td>
            <td><button type="button" value="8" class="calc">8</button></td>
            <td><button type="button" value="9" class="calc">9</button></td>
        </tr>
        <tr>
            <td><button type="button" value="0" class="calc">0</button></td>
            <td colspan="2"><button type="button" value="CLEAR" id="clear" class="calc">CLEAR</button></td>
        </tr>
    </table>
</main>
</body>
</html>
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-06-04 16:35:10

添加大量事件侦听器将妨碍应用程序的性能。因此,在这种情况下,您可以使用事件委托技术。如果你想读更多关于这个的文章,我发现此链接非常足智多谋。如果您有任何疑问,请在评论中找到我。

代码语言:javascript
复制
const input = document.querySelector("#user-input");
const table = document.querySelector("table");

table.addEventListener('click', (e) => {
    //Since we only want to register button clicks inside the table and not any clicks on the blank space between the buttons.
    if(e.target.tagName === "BUTTON") {
        if(e.target.id === "clear") {
            input.value = "";
        } else {
            input.value += e.target.value;
        }
    }
});
代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Async JS</title>
    <script src="promises.js" defer></script>
    <style>
        input {
            margin-top: 10px;
        }

        table {
            margin-bottom: 10px;
            width: auto;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <main>
        <input  id="user-input">
        <table>
            <tr>
                <td><button type="button" value="1" class="calc">1</button></td>
                <td><button type="button" value="2" class="calc">2</button></td>
                <td><button type="button" value="3" class="calc">3</button></td>
            </tr>
            <tr>
                <td><button type="button" value="4" class="calc">4</button></td>
                <td><button type="button" value="5" class="calc">5</button></td>
                <td><button type="button" value="6" class="calc">6</button></td>
            </tr>
            <tr>
                <td><button type="button" value="7" class="calc">7</button></td>
                <td><button type="button" value="8" class="calc">8</button></td>
                <td><button type="button" value="9" class="calc">9</button></td>
            </tr>
            <tr>
                <td><button type="button" value="0" class="calc">0</button></td>
                <td colspan="2"><button type="button" value="CLEAR" id="clear" class="calc">CLEAR</button></td>
            </tr>
        </table>
    </main>
</body>

</html>

票数 1
EN

Stack Overflow用户

发布于 2021-06-04 16:36:18

您可以/应该使用"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of“或"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in”循环。在这种情况下,for...of似乎是您所需要的。

代码语言:javascript
复制
const input = document.getElementById("user-input")

var buttons = document.querySelectorAll("td > button");
      for (var button of buttons) {
        button.addEventListener("click", function(e) { ... }

编辑:如果你想把每个数字连接到输入中(例如。( "123")用这个代替省略号:

代码语言:javascript
复制
  if (e.target.id === "clear") {
    input.value = "";
  } else {
    input.value += e.target.value;
  }
  document.getElementById("user-input").focus();

完整片段版本:

代码语言:javascript
复制
window.addEventListener("load", function() {
  const input = document.getElementById("user-input")
  var buttons = document.querySelectorAll("td > button");

  for (var button of buttons) {
    button.addEventListener("click", function(e) {
      if (e.target.id === "clear") {
        input.value = "";
      } else {
        input.value += e.target.value;
      }
      document.getElementById("user-input").focus();
    });
  }
});
代码语言:javascript
复制
input {
  margin-top: 10px;
}

table {
  margin-bottom: 10px;
  width: auto;
  margin-top: 10px;
}
代码语言:javascript
复制
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="stylesheet" href="../normalize.css">

  <title>Test</title>
</head>

<body>

  <main>
    <input id="user-input">
    <table>
      <tr>
        <td><button type="button" value="1" id="button-one" class="calc">1</button></td>
        <td><button type="button" value="2" class="calc">2</button></td>
        <td><button type="button" value="3" class="calc">3</button></td>
      </tr>
      <tr>
        <td><button type="button" value="4" class="calc">4</button></td>
        <td><button type="button" value="5" class="calc">5</button></td>
        <td><button type="button" value="6" class="calc">6</button></td>
      </tr>
      <tr>
        <td><button type="button" value="7" class="calc">7</button></td>
        <td><button type="button" value="8" class="calc">8</button></td>
        <td><button type="button" value="9" class="calc">9</button></td>
      </tr>
      <tr>
        <td><button type="button" value="0" class="calc">0</button></td>
        <td colspan="2"><button type="button" value="CLEAR" id="clear" class="calc">CLEAR</button></td>
      </tr>
    </table>
  </main>
</body>

</html>

票数 0
EN

Stack Overflow用户

发布于 2021-06-04 16:45:33

循环遍历按钮集合是完全有效的&将事件侦听器附加到其中的每一个按钮

代码语言:javascript
复制
window.addEventListener("load", function() {
  const userInput = document.getElementById("user-input")

  // get the collection of buttons -> OK
  var buttons = document.querySelectorAll("td > button");

  // in this for loop button is not a button object - it's just a NUMBER
  for (var button = 0; button < buttons.length; button++) {
    // you have to get access to the "button"th element in the buttons array
    // now THAT'S a button object -> you can attach an event listener to that
    buttons[button].addEventListener("click", function() {
      if (this.value === "CLEAR") {
        userInput.value = 0
      } else {
        // you have to cast the userInput's value to a number -> by default
        // that's not a number but a String!
        userInput.value = Number(userInput.value) + Number(this.value);
      }

      document.getElementById("user-input").focus();
    });
  }
});
代码语言:javascript
复制
input {
  margin-top: 10px;
}

table {
  margin-bottom: 10px;
  width: auto;
  margin-top: 10px;
}
代码语言:javascript
复制
<main>
  <input id="user-input" type="text" value="0">
  <table>
    <tr>
      <td><button type="button" value="1" class="calc">1</button></td>
      <td><button type="button" value="2" class="calc">2</button></td>
      <td><button type="button" value="3" class="calc">3</button></td>
    </tr>
    <tr>
      <td><button type="button" value="4" class="calc">4</button></td>
      <td><button type="button" value="5" class="calc">5</button></td>
      <td><button type="button" value="6" class="calc">6</button></td>
    </tr>
    <tr>
      <td><button type="button" value="7" class="calc">7</button></td>
      <td><button type="button" value="8" class="calc">8</button></td>
      <td><button type="button" value="9" class="calc">9</button></td>
    </tr>
    <tr>
      <td><button type="button" value="0" class="calc">0</button></td>
      <td colspan="2"><button type="button" value="CLEAR" id="clear" class="calc">CLEAR</button></td>
    </tr>
  </table>
</main>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67840686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档