简体   繁体   中英

How do I call an Object Function from an onClick Event?

I have a test.html which includes tree.js.

in this HTML I have

<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

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.

How can I generalize it, so the Object can get every name the coder wants to use?

Just define your own obj variable with the current instance, using closure for the event listener:

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

See also How to access the correct `this` context inside a callback? for a very similar manifestation of the problem (though you want to use the this of the handler).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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