如何在函数中调用 class 名称的所有实例?
How can I invoke all instances of a class name in a function?
我试图使具有相同 class 名称(“Cappy”)的所有元素在调用此函数时改变颜色,但我知道如何调用所有这些元素的唯一方法是通过用变量 (myPara) 和每个变量的索引号写出一行,由于其中有很多,这看起来很笨拙。有更简单的方法吗?
function mouseoverCaroline(){
var myPara = document.getElementsByClassName("Cappy");
myPara[0].style.backgroundColor = "red";
myPara[1].style.backgroundColor = "red";
myPara[0].style.color = "black";
myPara[1].style.color = "black";
myPara[0].style.borderColor = "#94a0b4";
myPara[1].style.borderColor = "#94a0b4";
}
像这样:
function mouseoverCaroline(className) {
var myPara = document.getElementsByClassName(className);
Array.from(myPara).forEach(element => {
element.style.backgroundColor = "red";
element.style.backgroundColor = "red";
element.style.color = "black";
element.style.color = "black";
element.style.borderColor = "#94a0b4";
element.style.borderColor = "#94a0b4";
});
}
div {
border: 1px solid black;
margin: 1px;
width: 100px;
}
<button onClick="mouseoverCaroline('Cappy')">Click Me</button>
<div class="Cappy">Div 1</div>
<div class="Cappy">Div 2</div>
<div class="Cappy">Div 3</div>
<div class="Cappy">Div 4</div>
<div class="Cappy">Div 5</div>
<div class="Cappy">Div 6</div>
我试图使具有相同 class 名称(“Cappy”)的所有元素在调用此函数时改变颜色,但我知道如何调用所有这些元素的唯一方法是通过用变量 (myPara) 和每个变量的索引号写出一行,由于其中有很多,这看起来很笨拙。有更简单的方法吗?
function mouseoverCaroline(){
var myPara = document.getElementsByClassName("Cappy");
myPara[0].style.backgroundColor = "red";
myPara[1].style.backgroundColor = "red";
myPara[0].style.color = "black";
myPara[1].style.color = "black";
myPara[0].style.borderColor = "#94a0b4";
myPara[1].style.borderColor = "#94a0b4";
}
像这样:
function mouseoverCaroline(className) {
var myPara = document.getElementsByClassName(className);
Array.from(myPara).forEach(element => {
element.style.backgroundColor = "red";
element.style.backgroundColor = "red";
element.style.color = "black";
element.style.color = "black";
element.style.borderColor = "#94a0b4";
element.style.borderColor = "#94a0b4";
});
}
div {
border: 1px solid black;
margin: 1px;
width: 100px;
}
<button onClick="mouseoverCaroline('Cappy')">Click Me</button>
<div class="Cappy">Div 1</div>
<div class="Cappy">Div 2</div>
<div class="Cappy">Div 3</div>
<div class="Cappy">Div 4</div>
<div class="Cappy">Div 5</div>
<div class="Cappy">Div 6</div>