如何仅使用JavaScript更改按钮的颜色onclick? [英] How to change button color onclick using javascript only?
问题描述
我试图使用onclick和getElementsByClassName更改按钮的颜色,并提出了类似这样的内容:
HTML:
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
JS:
function submitButtonStyle() {
document.getElementsByClassName("stylebutton").style.backgroundColor = "red"; }
如果你们能给我一些有关我的代码中缺少什么/我应该添加什么的信息,我将非常感激.
getElementsByClassName
返回HTMLCollection
,因此您需要使用索引来获取元素,在这种情况下,索引=== 0 getElementsByClassName[0]
.>
实际上,您不需要调用函数getElementsByClassName
,将元素作为参数传递.
function submitButtonStyle(_this) {
_this.style.backgroundColor = "red";
}
<button onclick="submitButtonStyle(this)" type="submit" class="stylebutton">
Submit </button>
使用事件绑定和功能querySelectorAll
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = "red";
})
});
<button type="submit" class="stylebutton"> Submit </button>
I was trying to make the color of the buttons change using onclick and getElementsByClassName and came up with something like this:
HTML:
<button onclick="submitButtonStyle()" type="submit" class="stylebutton">
Submit </button>
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.
getElementsByClassName
returns an HTMLCollection
so you need to get the elements using an index, in your case index === 0 getElementsByClassName[0]
.
Actually, you don't need to call the function getElementsByClassName
, pass the element as param.
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
document.querySelectorAll('.stylebutton').forEach(function(e) {
e.addEventListener('click', function() {
this.style.backgroundColor = "red";
})
});
<button type="submit" class="stylebutton"> Submit </button>
这篇关于如何仅使用JavaScript更改按钮的颜色onclick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!