[英]What is the best way to refactor this code?
What's a more effective way of writing the following code: 编写以下代码的更有效方法是什么:
<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");
}
}
I am using a for loop as a workaround for using multiple ID's on a single page (this is for a specific mockup - will not be used in production) 我使用for循环作为在单个页面上使用多个ID的解决方法(这是针对特定的模型 - 不会在生产中使用)
I am looking for a way to write this without using multiple change___() functions. 我正在寻找一种方法来编写它,而无需使用多个更改___()函数。
You could have the color as an argument to the function: 您可以将颜色作为函数的参数:
function changeColor(color) {
for (i = 0; i < myLoader.length; i++) {
myLoader[i].setAttribute("id", color);
}
}
Refactor so that u accept a color value on the function, and keep only one function to set the value 重构,以便你接受函数的颜色值,并只保留一个函数来设置值
<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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.