[英]How can you use one block of code to target all the classes on a website? (no jquery)
I've been working on a game as part of some class work and have run into an issue.作为课堂作业的一部分,我一直在开发一款游戏,但遇到了一个问题。 The issue is the code only effect one button.
问题是代码只影响一个按钮。 I'm using the following on a two '.restart' buttons to reload the browser....
我在两个“.restart”按钮上使用以下内容来重新加载浏览器....
//Reload Page
document.querySelector('.restart').addEventListener('click', function () {
location.reload();
});
One restart button is on the top(like a header).一个重启按钮在顶部(就像一个标题)。 The other is in a Modal.
另一个是在模态中。 The Modal shows up first in the HTML.
模态首先出现在 HTML 中。 I'm 99.9% this is why the second one gets skipped.
我是 99.9% 这就是为什么第二个被跳过的原因。 I've tried using
document.querySelectorAll....
However I get a Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function
and neither works.我试过使用
document.querySelectorAll....
但是我得到一个Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function
,也都Uncaught TypeError: document.querySelectorAll(...).addEventListener is not a function
。 How can I use one snippet to control all the same classes with Javascript?如何使用一个片段来控制所有相同的 Javascript 类? Below is a code pen of the game...
下面是游戏的代码笔...
https://codepen.io/AB3D/pen/xJWMpd https://codepen.io/AB3D/pen/xJWMpd
This happens because querySelectorAll()
returns an array of elements.发生这种情况是因为
querySelectorAll()
返回一个元素数组。
The solution would be to iterate through these elements and attach the event to each one of them.解决方案是遍历这些元素并将事件附加到它们中的每一个。
<button class="restart">Button 1</button> <button class="restart">Button 2</button> <button class="restart">Button 3</button> <script> var elements = document.querySelectorAll(".restart"); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("click", function() { location.reload(); }); } </script>
Since you're using a class name as a selector , you can also use getElementsByClassName("restart")
as an alternative , this method also returns an array of elements.由于您使用类名作为选择器,您也可以使用
getElementsByClassName("restart")
作为替代,此方法还返回一个元素数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.