请帮忙。我试图阻止播放按钮上的点击事件同时应用于所有div。我希望click事件仅适用于已被单击的div。请参阅下面的代码,了解我到目前为止的情况。我正在使用vanilla Javascript。
<style>
div{
width: 200px;
height: 200px;
border: 1px solid black;
}
.secondview{
background-color: blue;
}
.firstview{
visibility: hidden;
background-color: red;
}
</style>
<div class="secondview">
<button class="play"> Play </button>
<div class="firstview">
<p>Play this game </p>
<button id="submit"> Submit </button>
</div>
</div>
<div class="secondview">
<button id="btn" class="play"> Play </button>
<div class="firstview">
<p>Play this game </p>
<button id="submit"> Submit </button>
</div>
</div>
<div class="secondview">
<button class="play"> Play </button>
<div class="firstview">
<p>Play this game </p>
<button id="submit"> Submit </button>
</div>
</div>
<script>
var playBtn = document.getElementsByClassName("play");
for (var i=0; i<playBtn.length; i++){
playBtn[i].addEventListener("click", showQuestion)
}
var question = document.getElementsByClassName("firstview");
function showQuestion (){
for(j=0; j<question.length; j++){
question[j].style.visibility = "visible";
}
}
</script>
答案 0 :(得分:1)
在点击回调(不需要问号变量)之前,你不需要遍历“firstview”。
对于每次点击活动,您需要获取与单击按钮相关的“firstview”元素。
这是一个示例代码(增强此代码并验证每个步骤的null / undefine)
function showQuestion (el){
var view = el.target.parentElement.getElementsByClassName("firstview")[0];
view.style.visibility = "visible";
}