简体   繁体   English

如何从onClick事件中调用对象函数?

[英]How do I call an Object Function from an onClick Event?

I have a test.html which includes tree.js. 我有一个test.html,其中包括tree.js.

in this HTML I have 在这个HTML我有

<div id='forObj'></div>
<script type='text/javascript'>
var obj = new Tree(document.getElementById('forObj');
</script>

Inside the Tree.js File I have a function called 在Tree.js文件中我有一个名为的函数

this.draw
...
else
            {

                    div.onclick = function(){obj.eventFoo(this.id);};

            }

... ...

my Problem is: Now everyone has to refer to the Object obj, or this will not work. 我的问题是:现在每个人都必须引用Object obj,否则这将无效。

How can I generalize it, so the Object can get every name the coder wants to use? 我如何概括它,所以Object可以得到编码器想要使用的每个名字?

Just define your own obj variable with the current instance, using closure for the event listener: 只需使用当前实例定义您自己的obj变量,使用闭包为事件监听器:

… else {
    var obj = this;
    div.onclick = function(e) {
        obj.eventFoo(this.id);
    };
}

See also How to access the correct `this` context inside a callback? 另请参阅如何在回调中访问正确的`this`上下文? for a very similar manifestation of the problem (though you want to use the this of the handler). 对于问题的非常相似的表现(虽然你使用处理程序的this )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM