DOM_this keyword

假设我们有很多个buttons很多个h1s( querySelectorAll('button') ),用户任意点击一个h1 or button,那个h1/button就会产生随机的按钮背景颜色和字体颜色,对于button群体我们可以在点击事件内部写function,但是又需要对于h1群体单独写同样的function,会产生冗余,于是就有了this 关键词,可以在在一个单独的function里面使用,然后对于不同的群体,buttons/h1s分别进行调用。

const makeRandColor = () => {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r}, ${g}, ${b})`;
}

const buttons = document.querySelectorAll('button');

for (let button of buttons) {
    button.addEventListener('click', colorize)
}

const h1s = document.querySelectorAll('h1');
for (let h1 of h1s) {
    h1.addEventListener('click', colorize)
}

function colorize() {
    this.style.backgroundColor = makeRandColor();
    this.style.color = makeRandColor();
}
原文地址:https://www.cnblogs.com/LilyLiya/p/14307284.html