我希望在点击按钮时在“移动”类中获取文本,但我无法很好地获得文本。我的代码有什么问题吗?我想将文本传递给函数“move”。
for(var i=0; i<4; i++){
document.querySelectorAll("#my-card .moves button")[i].onclick = function(){
move(document.querySelectorAll("#my-card .moves .move")[i].textContent, gameID, playerID) };
}
我的部分HTML;
<div id="my-card">
<div class="hidden buffs"></div>
<div class="card-container">
<div class="card">
<img src="icons/normal.jpg" alt="type" class="type"/>
<span class="hp">60HP</span>
<h2 class="name">Pokemon Name</h2>
<div class="pokemon-pic">
<img src="images/pokeball.png" alt="pokemon" class="pokepic" />
</div>
<p class="info">Description here</p>
<div class="moves">
<button>
<span class="move">a</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">b</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">c</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">d</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>
<img src="icons/fighting.jpg" alt="weakness" class="weakness" />
</div>
答案 0 :(得分:0)
您可以将移动存储为按钮中的数据,然后单击从数据集中检索移动。
for (var i = 0; i < 4; i++) {
document.querySelectorAll("#my-card .moves button")[i].onclick = function(el) {
console.log(el.currentTarget.dataset.move);
}
}
&#13;
<div id="my-card">
<div class="hidden buffs"></div>
<div class="card-container">
<div class="card">
<img src="icons/normal.jpg" alt="type" class="type" />
<span class="hp">60HP</span>
<h2 class="name">Pokemon Name</h2>
<div class="pokemon-pic">
<img src="images/pokeball.png" alt="pokemon" class="pokepic" />
</div>
<p class="info">Description here</p>
<div class="moves">
<button data-move="a">
<span class="move">a</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button data-move="b">
<span class="move">b</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button data-move="c">
<span class="move">c</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button data-move="d">
<span class="move">d</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>
<img src="icons/fighting.jpg" alt="weakness" class="weakness" />
</div>
&#13;