[英]Change Multiple Classes with the same name using JavaScript?
Check out my small project on codepen below... 在下面查看我在Codepen上的小项目...
http://codepen.io/ajduff14/pen/DlHge http://codepen.io/ajduff14/pen/DlHge
Basically I'm just testing out my JavaScript knowledge and I want to learn how to change all the buttons to the same class and use JavaScript to input a color that will change the background color of all the buttons with the given class "buttons". 基本上,我只是测试我的JavaScript知识,我想学习如何将所有按钮更改为同一类,并使用JavaScript输入一种颜色,该颜色将更改给定类“按钮”中所有按钮的背景色。 I can only manage to get it to work for 1 class at a time but not several.
我只能设法让它一次只能上一堂课,而不能上几堂课。
It's probably a simple answer but I've done quite a bit of digging for it already and I can't find one! 这可能是一个简单的答案,但是我已经对其进行了很多挖掘,但我找不到! Could someone please help?
有人可以帮忙吗?
Thanks, 谢谢,
Adam 亚当
There is no way to change classes or styles on many elements at the same time, you'll have to iterate and apply it to one element at a time 无法同时更改多个元素上的类或样式,您必须一次迭代并将其应用于一个元素
var buttons = document.querySelectorAll('.buttons');
for (var i=0; i<buttons.length; i++) {
buttons[i].style.background = 'red';
buttons[i].className = buttons[i].className + ' newclass';
}
There were some trivial mistakes in your HTML and JS code. 您的HTML和JS代码中有一些琐碎的错误。
1) In many places, instead of class="buttons" for input tag, you specified it as id="buttons". 1)在许多地方,您将输入标签指定为id =“ buttons”而不是class =“ buttons”。 Remember that you should have a unique id for each element.
请记住,每个元素应具有唯一的ID。
2) You were setting the style.backgroundColor property for buttons[3] and not for all objects with class name buttons. 2)您正在为button [3]而不是为所有带有类名按钮的对象设置style.backgroundColor属性。
document.getElementsByClassName('buttons') gets you an array of objects with class name "buttons." document.getElementsByClassName('buttons')为您提供一个类名称为“ buttons”的对象数组。 You need to iterate over every element of this array and set its background color property to appropriate value.
您需要遍历此数组的每个元素,并将其背景颜色属性设置为适当的值。
You could use a for-in loop or a standard for loop to achieve this purpose. 您可以使用for-in循环或标准的for循环来实现此目的。 I have used the for-in loop.
我使用了for-in循环。
for (button in buttons) {
buttons[button].style.backgroundColor = div2.children[0].value;
}
See this link for a working copy of your project: http://jsfiddle.net/mayank_agarwal/LaQuz/ 请参阅此链接以获取项目的工作副本: http : //jsfiddle.net/mayank_agarwal/LaQuz/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.