JS:什么函数会让我的代码变干?



My Program
最初在黑色网格上绘制的蚀刻草图。用户单击">擦除"以在黑色方块上着色。用户也可以点击**彩虹"在每个方块上随机绘制颜色,即正方形[0]可以是蓝色,正方形[1]可以是紫色......等等,它们在每次鼠标悬停时都是随机的。

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

目标如果你看看我在底部注释掉的函数,我试着想出一些我可以同时用于eraseGrid((和drawRainbow((的东西,但是在测试函数时,它没有按预期工作。它不会在每次鼠标悬停时绘制随机颜色,而是创建一种随机颜色(假设蓝色(并在网格上绘制蓝色。如果我重新打开彩虹,它会创建另一种随机颜色(例如绿色(并在网格上绘制。
我不明白为什么我创建的函数没有按预期工作,而重复的代码却按预期工作。


/**************************** 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');
})
}
}*/

至于注释掉的 changeColor 函数,如果你把彩虹和擦除放在父对象中,这样你就可以按名称找到它们,你应该能够像这样重构它。

const objects = {erase, rainbox};
function changeColor(str1, str2) { 
objects[str1].classList.toggle(str1);
if (objects[str1].className === str1) {
objecs[str2].classList.remove(str2);
main.addEventListener('mouseover', function(){
pickColor('rgb(' + randColor() + ')');
})
}
else {
main.addEventListener('mouseover', function(){
pickColor('#333');
})
}
}

同样,正如@me_评论中提到的。每次点击时添加事件侦听器很可能不是您想要的。第五次点击后,您将有五个事件监听器,以及五个函数function(){pickColor('rgb(' + randColor() + ')');}每次将鼠标悬停在"main"上时都会调用它们(每次点击都会扩展......

(编辑是因为评论非常严格:(

00Saad:我看到有一个 removeEventListener(( 方法,我会通过在 addEventListener 之后添加 main.removeEventListener('mouseover', function(({ pickColor('rgb(' + randColor(( + '('(; }( 来实现它吗?

不,如果您希望以后能够轻松删除函数,请将函数存储在变量中。

function(){...}<-- 这是创建新函数的代码段。 所以这个:main.removeEventListener('mouseover', function(){...}),将创建一个新的匿名函数,并尝试从main的事件侦听器中删除(如果它不存在(。

此外,如果您使用存储函数(const a = function(){..}(和更高addEventListener('mouseover', a)(,这将解决问题,因为无论如何您都无法将同一函数多次绑定到同一事件(它不会有任何效果(。

但是,接下来的addEventListener-调用将没有区别,因此在您的情况下,将鼠标悬停侦听器置于changeColor()范围之外会更有意义。

let isRandomColor = true;
main.addEventListener('mouseover', function(){
pickColor( isRandomColor ? randomColor() : '#333' );
});
function changeColor(){
if (...){
isRandomColor = true;
} else {
isRandomColor = false;
}
}

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

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');
}

最新更新