0

Maybe there are serval sub-questions for my problem:

  • Is there a general solution to get events binded to an element?(Without jquery or others javascript librarys).
  • I found $(element).data('events') can't get event registered with <element onclick="some_functions()">. How can we get it?

My goal is to insert an event before native event (registered by the programmer of html page). I found two solutions.

However, I find both these methods can't solve the situation like that

<element onclick="some_functions()">
4

1 回答 1

0

onclick您可以通过该属性访问(和覆盖)该事件处理程序。如果你有一个

<span id="elem" onclick="some_functions()">

然后document.getElementById("elem").onclick将产生匿名函数

function (event) {
    some_functions()
}

要拦截它,您可以使用类似

var fn = elem.onclick;
elem.onclick = function() {
    console.log("before");
    var res = fn.apply(this, arguments);
    console.log("after");
    return res;
};

免责声明:这可能不会在较旧的浏览器中,我不知道内联属性事件处理程序和传统事件注册的发明者(Netscape,IE)如何处理这些。他们还不如做过类似的事情eval(elem.getAttribute("onclick")),在任何情况下,您都可以像这样访问处理程序代码(作为字符串)。

于 2013-05-06T12:26:49.317 回答