首页 > 其他 > 详细

DOM_this keyword

时间:2021-01-21 12:57:18      阅读:44      评论:0      收藏:0      [点我收藏+]

假设我们有很多个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();
}

 

DOM_this keyword

原文:https://www.cnblogs.com/LilyLiya/p/14307284.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!