JS - this As A DOM Event Handler

博客介绍了编程中事件和事件处理程序的概念。事件是用户或其他来源触发的动作,如鼠标点击、按键等;事件处理程序是用于处理事件的例程,程序员可编写在事件发生时执行的代码,还提到了作为DOM事件处理程序的情况。

n programming, an event is an action that occurs as a result of the user or another source, such as a mouse being clicked, or a key being pressed. 

An event handler is a routine that is used to deal with the event, allowing a programmer to write code that will be executed when the event occurs.

As a DOM event handler

When a function (bluify below) is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener()).

// When called as a listener, turns the related element blue
function bluify(e) {
  // Always true
  console.log(this === e.currentTarget); 
  // true when currentTarget and target are the same object
  console.log(this === e.target);
  this.style.backgroundColor = '#A5D9F3';
}

// Get a list of every element in the document
var elements = document.getElementsByTagName('*');

// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener('click', bluify, false);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值