编写以下代码的更有效的方法是什么:
<button onclick="changeRed()">red</button>
<button onclick="changeGray()">gray</button>
<button onclick="changeBlack()">black</button>
myLoader = document.getElementsByClassName('preloader');
function changeGray() {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", "gray");
}
}
function changeBlack() {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", "black");
}
}
function changeRed() {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", "red");
}
}我使用for循环作为在单个页面上使用多个ID的变通方法(这是用于特定的模型-不会在生产中使用)
我正在寻找一种不使用多个change___()函数来编写代码的方法。
发布于 2019-07-16 05:12:16
您可以将颜色作为函数的参数:
function changeColor(color) {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", color);
}
}发布于 2019-07-16 05:12:47
重构,以便您接受函数的颜色值,并只保留一个函数来设置值
<button onclick="setColor('red')">red</button>
<button onclick="setColor('gray')">gray</button>
<button onclick="setColor('black')">black</button>
myLoader = document.getElementsByClassName('preloader');
function setColor(color) {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", color);
myLoader[i].setAttribute("style", 'color:'+color);
}
}https://stackoverflow.com/questions/57047197
复制相似问题