我想在第二个“移动”类中的第3个按钮元素中添加一个“隐藏”类。我的代码中有什么问题吗?感谢。
document.getElementsByClassName("moves")[1].getElementsByTagName("button")[4].classList.add("hidden");
html如下; 附:我刚刚更改了这个问题的索引以简化我的问题。所以不要介意索引。
<div class="moves">
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>
答案 0 :(得分:1)
<强>更新强> 根据你提供的UI看,只有'移动'类只有四个按钮。因此索引位置将在您的JavaScript代码中更新。 就像在getElementsByClassName中一样,索引位置将从0开始,即getElementsByClassName [0]。类似地,在getElementByTagName索引位置将从0开始。所以你必须更新'3'处的索引,'3'指的是你的最后一个按钮。
根据我之前的回答,有5个按钮,所以我使用了索引位置4。
document.getElementsByClassName("moves")[0].getElementsByTagName("button")[3].classList.add("hidden");
<div class="moves">
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
<button>
<span class="move">Move Name Here</span> <span class="dp"></span>
<img src="icons/fighting.jpg" alt="Pokemon move" />
</button>
</div>
看下面的代码片段,我认为是这个场景。你编写我们的工作正常,类被添加到元素。检查那个元素,你会看到它
document.getElementsByClassName("moves")[1].getElementsByTagName("button")[3].classList.add("hidden");
<div class="moves">
first
</div>
<div class="moves">
second
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
</div>
答案 1 :(得分:0)
第4个按钮实际上是索引号 3 。将 4 更改为 3 ,您就完成了。
document.getElementsByClassName("moves")[1].getElementsByTagName("button")[3].classList.add("hidden");
您说我们不应该担心索引,但您提供的索引会导致您的HTML
出错。没有第5个按钮。