简体   繁体   中英

Get event target from within javascript module

I'm using the revealing module pattern for the first time and gradually getting to grips with it.

In my html I have something like this:

<a href='#' onclick='myApp.doStuff'>Click here</a>

In javascript I have:

var myApp = (function () {

    var doStuff = function() {
        //Get clicked element and modify it with jQuery?
    }

    return {
        doStuff: doStuff
    }

})();

How do I get the clicked element at the point indicated above?

You can use jQuery methods, like alex23 said.

But you can also write in html:

<a href='#' onclick='myApp.doStuff(this)'>Click here</a>

and this for your javascript:

var myApp = (function () {

    var doStuff = function(elem) {
        //use the element here
    }

    return {
        doStuff: doStuff
    }

})();




If you want to pass the event object, too, extend the call in onclick to:

onclick='myApp.doStuff(this, event)'

and the javascript to:

...
var doStuff = function(elem, event){
...
}

Use jQuery event handling for that. Cross browser event handling is not a trivial matter in JavaScript.

Say you have:

<a id="someLink" ..etc>Click here</a>
$("#someLink").click(function(event) {
   $(this).html("I have been clicked");
});

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