• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
DOM_this keyword
DOM里面的function里面使用this关键词

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

 

posted on 2021-01-21 12:05  LilyLiya  阅读(92)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3