我正在学习 javascript,我认为最好的学习方法是制作 TicTacToe 游戏(在此之前我制作了其他非常基础的 JavaScript)。
我想知道他们是否是比我目前正在尝试做的更简单的解决方案。
如果用户想成为“x”或“o”,我会给他们一个选择。如果他们选择“x”或“o”,我有两个单独的函数会触发。
有没有一种方法可以让我只有一个函数来检测是否选择了“x”或“o”,然后在该选择之后立即开始另一个函数? (我认为这将是绘制井字板的功能)。
你可以看到我在玩弄 var userChoiceO=document.GetElementById("O");
和 w.addEventListener("click", userChoice);
但我仍在学习,其中一些正在我脑海中浮现。
如果我朝着正确的方向前进,任何类型的建议都将不胜感激。
这里是我到目前为止所得到的总体思路:
var userShape = 'X';
var playerX=document.getElementById("X");
var playerO=document.getElementById("O");
function userChoiceX () {
userShape = 'X';
}
function userChoiceO() {
userShape = '0';
}
.XO {
font-size:70px;
text-align: center;
}
#X {
color:#ff574f;
cursor: pointer;
text-align: center;
margin-right: 6vw;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
}
#X:hover {
font-size:100px;
}
#O {
color:#8cabec;
cursor: pointer;
text-align: center;
margin-left: 6vw;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
}
#O:hover {
font-size:100px;
}
<p>Click on the shape you would like to play as</p>
<div class="XO">
<span id="X" class="X" onclick="userChoiceX()">X</span><span id="O" class="O" onclick="userChoiceO()">O</span>
</div>
最佳答案
您可以将事件处理程序与两个跨度的父级绑定(bind) <div class="XO" onclick="userChoice(event);">
,
然后,event.target
为您提供点击的跨度元素:
function userChoice(event) {
if (event.target.id == 'X')
return userChoiceX();
else if (event.target.id == 'O')
return userChoiceO();
}
var userShape = 'X';
var players=document.querySelector(".XO");
function userChoice(event) {
if (event.target.id == 'X')
return userChoiceX();
else if (event.target.id == 'O')
return userChoiceO();
}
function userChoiceX () {
userShape = 'X';
}
function userChoiceO() {
userShape = '0';
}
.XO {
font-size:70px;
text-align: center;
}
#X {
color:#ff574f;
cursor: pointer;
text-align: center;
margin-right: 6vw;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
}
#X:hover {
font-size:100px;
}
#O {
color:#8cabec;
cursor: pointer;
text-align: center;
margin-left: 6vw;
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
}
#O:hover {
font-size:100px;
}
<p>Click on the shape you would like to play as</p>
<div class="XO" onclick="userChoice(event);">
<span id="X" class="X" >X</span><span id="O" class="O" >O</span>
</div>
关于javascript - 学习 Javascript - 监听两种选择的 onclick 事件的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151842/