複数のクラスがある場合、クラス名をクリックして関数を呼び出すにはどうすればよいですか?私のコードでは、私は1つをクリックするたびに関数を呼びたいクラスボックスが9つあります。複数クラスのJavascript onclickイベントハンドラ
<!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 {
\t \t \t margin: 0 auto;
\t \t }*/
.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>
私はES6の構文に精通していない人たちの答えを明確にするべきだと思います。 –
@AlexeyUkolovが更新されました。私は小さな記法を思いつくことができると知っていました:) – mido
[ブラウザのサポート](http://kangax.github.io/compat-table/es6/#test-spread_(...)_operator)forスプレッドは驚くほど良く、イベントは矢印機能より優れています。 –