多个类上的Javascript onclick事件处理程序

Javascript onclick event handler on multiple classes

本文关键字:onclick 事件处理 程序 Javascript      更新时间:2023-09-26

当我有多个类时,如何单击类名并调用函数?在我的代码中,我有9个类框,每次点击一个,我都想调用一个函数。

<!DOCTYPE html>
<html>
<head>
  <title>Tic Tac Toe Game</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #container {
      width: 303px;
      margin: 0 auto;
      margin-top: 40px;
    }
    h1 {
      text-align: center;
      margin-bottom: 15px;
    }
    /*#wrapper {
			margin: 0 auto;
		}*/
    .col {
      float: left;
      margin: 0 auto;
    }
    .col > div:nth-child(-n+1) {
      border-bottom: 1px solid #000;
    }
    .col > div:nth-child(-n+2) {
      border-bottom: 1px solid #000;
    }
    .col > div {
      border-right: 1px solid #000;
    }
    .col:last-child {
      border-right: none;
      border: 1px solid red;
    }
    #wrapper.col * {
      border-right: none;
    }
    .reset {
      clear: both;
    }
    .box {
      width: 100px;
      height: 100px;
      background-color: grey;
      font-size: 80px;
      text-align: center;
    }
    body {
      font-size: 80%;
    }
  </style>
</head>
<body>
  <div id="container">
    <h1>Tic Tac Toe</h1>
    <div id="wrapper">
      <div class="col">
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
      </div>
      <div class="col">
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
      </div>
      <div class="col">
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
      </div>
      <div class="reset"></div>
    </div>
  </div>
  <script>
    var turnsArray = [];
    function player() {
      alert("hello");
    }
    var el = document.getElementsByClassName('box');
    el.onclick = player;
  </script>
</body>
</html>

getElementsByClassName返回HTMLCollection,而不是单个元素,因此不能直接将事件处理程序附加到它
您需要迭代这个集合,并为每个元素设置事件事件处理程序:

items = document.getElementsByClassName('box');
[].forEach.call(items, function (el) {
  el.addEventListener('click', player);
});

HTMLCollection不是一个合适的数组,所以你不能直接在它上调用forEach方法,但你可以在数组上调用forEach并将集合传递给它。

[]。slice用于将调用结果转换为新数组。因此,您可以使用forEach

 var el = document.getElementsByClassName('box');
    el_arr = [].slice.call(el);
    el_arr.forEach(function(obj,i){
    obj.addEventListener("click",function(){
        player();
         });
    });

el给出了一个HTMLCollection,所以你需要在每个上迭代并设置onclick监听器,在ES6中,你可以简单地通过[...el]将HTMLCollection转换为数组,所以代码变成:

var el = document.querySelectorAll('.box');
[...el].forEach(e => e.onclick = player)

Fiddle演示