gpt4 book ai didi

javascript - 如何通过类获取跨度内的文本。 (for循环内部)

转载 作者:行者123 更新时间:2023-12-01 03:40:46 27 4
gpt4 key购买 nike

我想在具有类move的跨度内获取文本。因此,我试图使当您单击按钮时,类 move 内的文本作为参数之一传递给函数 move 。附注HTML 代码已给出,我无法对其进行任何更改。我的js代码有问题吗?错误消息显示“未捕获类型错误:无法读取未定义的属性‘innerHTML’”。

部分 HTML 代码;

 <div id="my-card">


<div class="card-container">
<div class="card">
<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>
</div>
</div>

Javascript:

   for(var i=0; i<4; i++){
document.querySelectorAll("#my-card .moves button")[i].onclick = function(){ move(document.querySelectorAll("#my-card .moves .move")[i].innerHTML, gameID, playerID) };
}

最佳答案

试试这个

 for(var i=0; i<4; i++){
document.querySelectorAll("#my-card .moves button")[i].onclick =
function(){ move(this.querySelectorAll(".move")[0].innerHTML, gameID, playerID) };
}

我将您的 document.querySelectorAll 切换为 this.querySelectorAll

下面是向控制台显示结果的代码片段。

for (var i = 0; i < 4; i++) {
document.querySelectorAll("#my-card .moves button")[i].onclick = function() {

console.log(this.querySelectorAll(".move")[0].innerHTML)

}
}
<div id="my-card">


<div class="card-container">
<div class="card">
<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>
</div>
</div>

关于javascript - 如何通过类获取跨度内的文本。 (for循环内部),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905306/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com