3

当前代码

<a onclick="callMe1()">Click Me</a>
<a onclick="callMe2()">Click Me 2</a>

function callMe(){
   //anything
}

function callMe2(){
   //anything
}

等等...我有数百个 onclick 事件函数。

我想添加这个应该在任何 onclick 事件函数之前调用的函数。

function callBeforeAnyOnClick(){
//This should be executed before callMe() and callMe2().
//once execution is complete, it should call a function as per onclick event,callMe() or callMe2().
}

有什么解决办法吗?jquery 绑定会在这里工作吗?

4

3 回答 3

0

The way the DOM + JS works, you can't "hijack" the order of execution when mixing/matching library (jquery) event handling and inline script event handling. Two things come to mind:

  1. Use a mousedown/up event, which will fire before the click event.
  2. Modify/manipulate the DOM with jquery after load so you have more control.

Pseudo Example of option #2:

$(function()
{

  $('a[onclick]').click(function() { /* your normal on click here */ });

  // now modify the DOM to convert the onclick attr into a function call
  $('a[onclick]').each(function()
  {
    var clickFunction = $(this).attr('onclick');

    // remove the attr
    $(this).attr('onclick', '');

    // might be a better way than calling eval on the inline function, but this serves its purpose for the demo
    $(this).click(function() { eval(clickFunction); });
  });
});

So in the above example, I remove the onclick attr and conver it to a jquery click event handler, and I do it second, not first, so it happens after my newly inserted pre-onclick function.

于 2012-12-04T13:04:24.467 回答
0

您正在寻找的是观察者模式的经典示例。这在 javascript 中很难实现,特别是如果将 JS 与 jQuery 混合使用,还因为您想要监听的是事件(本身就是观察者)。我会在文档上添加一个侦听器,并且仅在为元素定义了 onclick 函数时才执行它(注意:如果您使用 jQuery 中的 .on 添加事件侦听器,这将不起作用):

function observerMethod(e) {
  if (e.target.onclick) {
    ... do your thing here ...
  }
}

document.addEventListener("click", observerMethod, false);
于 2012-12-04T13:20:36.197 回答
0

您可以调用“调度程序”函数传递您需要调用的真实函数,例如

<a onclick="callfun(f1)">Click Me</a>
<a onclick="callfun(f2)">Click Me 2</a>

function f1 { console.log("Hello f1"); }
function f2 { console.log("Hello f2"); }

function callfun(f){
   /* do something before */

   if ('function' === typeof f) {
     f();
   }
}
于 2012-12-04T13:00:34.273 回答