如何仅使用 javascript 更改按钮颜色 onclick?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48845033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change button color onclick using javascript only?
提问by skrttt44
I was trying to make the color of the buttons change using onclick and getElementsByClassName and came up with something like this:
我试图使用 onclick 和 getElementsByClassName 改变按钮的颜色,并想出了这样的事情:
HTML:
HTML:
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
JS:
function submitButtonStyle() {
document.getElementsByClassName("stylebutton").style.backgroundColor = "red"; }?
I would be really grateful if you guys gave me a hint about what is lacking in my code/what I should add etc.
如果你们给我一个关于我的代码中缺少什么/我应该添加什么等的提示,我将非常感激。
回答by Ele
getElementsByClassNamereturns an HTMLCollectionso you need to get the elements using an index, in your case index === 0 getElementsByClassName[0].
getElementsByClassName返回一个HTMLCollection所以你需要使用索引来获取元素,在你的情况下 index === 0 getElementsByClassName[0]。
Actually, you don't need to call the function getElementsByClassName, pass the element as param.
实际上,您不需要调用函数getElementsByClassName,将元素作为参数传递。
function submitButtonStyle(_this) {
_this.style.backgroundColor = "red";
}
<button onclick="submitButtonStyle(this)" type="submit" class="stylebutton">
Submit </button>
Better approach using Event binding and function querySelectorAll
使用事件绑定和函数的更好方法 querySelectorAll
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = "red";
})
});
<button type="submit" class="stylebutton"> Submit </button>
回答by NieDzejkob
document.getElementsByClassNamereturns an array of objects, since many tags may have the same class. If you know that only one object has a given class, use
document.getElementsByClassName返回一个对象数组,因为许多标签可能具有相同的类。如果您知道只有一个对象具有给定的类,请使用
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red";
回答by jasinth premkumar
The className property sets or returns the class name of an element (the value of an element's class attribute).
className 属性设置或返回元素的类名(元素的类属性值)。
function submitButtonStyle() {
document.getElementsByClassName("stylebutton")[0].style.backgroundColor = "red"; }
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
getElementsByClassName() 方法返回文档中具有指定类名的所有元素的集合,作为 NodeList 对象。
NodeList 对象表示节点的集合。可以通过索引号访问节点。索引从 0 开始。

