首页 > 解决方案 > JS:什么函数会使我的代码干燥?

问题描述

我的程序
最初在黑色网格上绘制的 Etch-A-Sketch。用户单击擦除以在黑色方块上着色。用户也可以点击 **Rainbow" 在每个方块上绘制随机颜色,即 square[0] 可以是蓝色,square[1] 可以是紫色……等等,它们在每次mouseover时都是随机的。

问题 您会注意到eraseGrid()drawRainbow()的代码几乎相同。我必须这样做,否则程序将无法正常工作。这是Rainbow在每次鼠标悬停时绘制不同颜色的唯一方法。

目标 如果您查看我在底部注释掉的函数,我尝试想出一些可以用于eraseGrid()drawRainbow()的东西,但是在测试该函数时,它没有按预期工作。它不会在每个mouseover上绘制随机颜色,而是创建随机颜色(比如说蓝色)并在网格上绘制蓝色。如果我重新打开Rainbow,它将创建另一种随机颜色(例如绿色)并将其绘制在网格上。
我不明白为什么我创建的函数不能按预期工作,而重复的代码却可以。


/**************************** Input->Button DOM ****************************/

const newGrid = document.getElementById('new-grid');
newGrid.addEventListener('click', createGrid);

const erase = document.getElementById('erase');
erase.addEventListener('click', eraseGrid);

const rainbow = document.getElementById('rainbow');
rainbow.addEventListener('click', drawRainbow);

/*********************** Grid variable and creation ***********************/

const main = document.querySelector('main');
const div = main.getElementsByTagName('div');

drawGrid(16, ((600 / 16) - 2) + 'px');
pickColor('#333');

function createGrid() {

    // removes divs from largest to smallest
    for (let i = main.childNodes.length - 1; i >= 0 ; i--) {
        main.removeChild(main.childNodes[i]);
    }

    let size;
    do {
        size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);
    } while(Number.isNaN(size) || size > 64 || size < 1);

    const numPx = (600 / size) - 2;
    let px = numPx + 'px';

    drawGrid(size, px);
    pickColor('#333');
}


function pickColor(color) {
    for (let i = 0; i < main.childNodes.length; i++) {
        main.childNodes[i].addEventListener('mouseover', function change() {
            main.childNodes[i].style.backgroundColor = color;
        })
    }
}

// draw grid of div elements
function drawGrid(size, px) {
    for (let i = 0; i < size; i++) {
        for (let j = 0; j < size; j++) {
            const div = document.createElement('div');
            main.appendChild(div);
            div.setAttribute('style', `width: ${px}; height: ${px}; 
                float: left; border: 1px solid #333;`);
        }
    }

    // clear floats
    const div = document.createElement('div');
    div.setAttribute('class', 'clear');
    main.appendChild(div);
}

function eraseGrid() {
    erase.classList.toggle('erase');
    if (erase.className === 'erase') {
        rainbow.classList.remove('rainbow');
        main.addEventListener('mouseover', function(){
            pickColor('#f2f2f2');
        })
    }
    else {
        main.addEventListener('mouseover', function(){
            pickColor('#333');
        })
    }
}

function randColor() {
    let arr = [];
    for (let i = 0; i < 3; i++) {
        arr.push(Math.floor(Math.random() * 255));
    }
    return arr;
}

function drawRainbow() {
    rainbow.classList.toggle('rainbow');
    if (rainbow.className === 'rainbow') {
        erase.classList.remove('erase');
        main.addEventListener('mouseover', function(){
            pickColor('rgb(' + randColor() + ')');
        })
    }
    else {
        main.addEventListener('mouseover', function(){
            pickColor('#333');
        })
    }
    // changeColor(rainbow, 'rainbow', erase, 'erase', 'rgb(' + randColor() + ')')
}

/*function changeColor(newClass, newClassStr, oldClass, oldClassStr, color) {
    newClass.classList.toggle(newClassStr);
    if (newClass.className === newClassStr) {
        oldClass.classList.remove(oldClassStr);
        main.addEventListener('mouseover', function(){
            pickColor(color);
        })
    }
    else {
        main.addEventListener('mouseover', function(){
            pickColor('#333');
        })
    }
}*/

标签: javascriptfunctiondry

解决方案


你可以算出名字,但看起来你只是在做

function go(str1, str2){
    document.getElementById(str1).classList.toggle(str1);
    if (document.getElementById(str1).className === str1) {
        document.getElementById(str2).classList.remove(str2);
        main.addEventListener('mouseover', function(){
            pickColor('#f2f2f2');
        })
    }
    else {
        main.addEventListener('mouseover', function(){
            pickColor('#333');
        })
    }
}

只需调用它go('erase', 'rainbow')go('rainbow', 'erase')

function eraseGrid(){
    go('erase', 'rainbow');
}

function drawRainbow(){
    go('rainbow', 'erase');
}

推荐阅读