我想在您点击按钮时,代码应该提醒类移动内的名称。但我的代码无法正常工作,并且控制台说“无法读取未定义的属性'getElementsByClassName'”。我的javascript代码有什么问题吗?感谢。
我的部分JavaScript代码;
<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>
我的部分HTML代码;
categories
答案 0 :(得分:0)
有几点需要注意:
1 - 当您将alert()
传递给点击处理程序时,会立即调用它。你需要将它包装在一个函数中。
2 - 使用this
,您不需要从最顶层重新选择元素,您可以从目前在该范围内的位置开始。
for (var i = 0; i < 4; i++) {
document.getElementsByClassName("moves")[0].getElementsByTagName("BUTTON")[i].onclick = function() {
alert(this.textContent.trim())
};
}
&#13;
<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>
&#13;