将此传递给addEventListener()作为参数 [英] Pass this to addEventListener() as parameter

查看:69
本文介绍了将此传递给addEventListener()作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将更改事件添加到一组复选框中,如何在我的事件函数中访问 ,所以当我做事件时,我可以访问复选框的值。

I want to add change event to a group of checkboxes, how can I access this in my event function, so that when I do the event I can access value of the checkbox.

这是我当前的代码。

This is my current code.

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(){
  this.addEventListener("change", cbChange(this), false);
});

function cbChange(ele){
  console.log(ele.value);
}

<input class="cb" type="checkbox" name="candidate" value="1"/>
<input class="cb" type="checkbox" name="candidate" value="2"/>
<input class="cb" type="checkbox" name="candidate" value="3"/>
<input class="cb" type="checkbox" name="candidate" value="4"/>

推荐答案

forEach 回调中,这个 引用DOM元素。它没有引用任何有用的值。

Inside the forEach callback, this does not refer to a DOM element. It doesn't refer to any useful value.

其次,您立即调用 cbChange 并传递其返回值到 addEventListener ,这是 undefined 。但 addEventListener 期望传递函数,因此您必须传递 cbChange 或调用 cbChange 的函数。

Secondly, you are immediately calling cbChange and pass its return value to addEventListener, which is undefined. But addEventListener expects to be passed a function, so you either have to pass cbChange or a function that calls cbChange.

最后,您可以定义事件处理程序以接受该元素作为第一个参数,如果接受事件对象,则会更简单,因为这是默认的API。

Lastly, while you could define the event handler to accept the element as first argument, it's much simpler if it accepts the event object, because that is the default API.

说了这么多,最简单的解决方案就是:

Having said all that, the simplest solution would be:

var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
//                                      ^^^^^^^
  element.addEventListener("change", cbChange, false);
//^^^^^^^  
});

function cbChange(){
  console.log(this.value);
//            ^^^^
}

因为在事件处理程序中, 引用处理程序绑定的元素,在 cbChange this c $ c>正常工作。

Since inside an event handler, this refers to the element the handler is bound to, using this inside cbChange just works.

这里有一些选择:

// Use the event object
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", cbChange, false);
});

function cbChange(event){
  console.log(event.target.value);
}


// Using a wrapper that calls `cbChange`
var checkboxes = document.getElementsByClassName('cb');
Array.from(checkboxes).forEach(function(element){
  element.addEventListener("change", function() { cbChange(this); }, false);
});

function cbChange(ele){
  console.log(ele.value);
}

这篇关于将此传递给addEventListener()作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆