简体   繁体   English

从javascript模块中获取事件目标

[英]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: 在我的HTML中我有这样的事情:

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

In javascript I have: 在javascript我有:

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. 你可以使用jQuery方法,比如alex23说。

But you can also write in html: 但你也可以用html写:

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

and this for your javascript: 这对你的javascript:

var myApp = (function () {

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

    return {
        doStuff: doStuff
    }

})();


Update 更新

If you want to pass the event object, too, extend the call in onclick to: 如果您也想传递事件对象,请将onclick中的调用扩展为:

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

and the javascript to: 和javascript:

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

Use jQuery event handling for that. 使用jQuery事件处理。 Cross browser event handling is not a trivial matter in JavaScript. 跨浏览器事件处理在JavaScript中不是一件小事。

Say you have: 说你有:

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

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

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