本文介绍了在addeventlistener中使用此关键字调用javascript类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过addEventListener调用类"Example"中的函数getItemList()

I want to call the function getItemList() which is in a class 'Example' through addEventListener

var text_box = document.getElementById(this.text_box_id);
text_box.addEventListener('onchange', function(){this.getItemList('3', '10')}, false) 

推荐答案

应为change,而不是onchange.仅在IE中,您必须使用on(EventName).

It should be change, not onchange. Only in IE you have to use on(EventName).

this将引用text_box(引发事件的元素).您必须捕获对当前this的引用:

this inside the handler will refer to text_box (the element the event was raised on). You have to capture a reference to the current this:

var that = this;
text_box.addEventListener('change', function(){    
    that.getItemList('3', '10')
}, false);

或在支持 bind 的浏览器中(您可以还提供了本文档中所示的您自己的实现):

Or in browsers supporting bind (you can also provide your own implementation as shown in this documentation):

text_box.addEventListener('change', function(){    
    this.getItemList('3', '10')
}.bind(this), false);

这篇关于在addeventlistener中使用此关键字调用javascript类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 11:00