簡體   English   中英

重構此代碼的最佳方法是什么?

[英]What is the best way to refactor this 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");
        }
    }

我使用for循環作為在單個頁面上使用多個ID的解決方法(這是針對特定的模型 - 不會在生產中使用)

我正在尋找一種方法來編寫它,而無需使用多個更改___()函數。

您可以將顏色作為函數的參數:

    function changeColor(color) {
        for (i = 0; i < myLoader.length; i++) {
            myLoader[i].setAttribute("id", color);
        }
    }

重構,以便你接受函數的顏色值,並只保留一個函數來設置值

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM