代码之家  ›  专栏  ›  技术社区  ›  sirrocco

拦截javascript事件

  •  1
  • sirrocco  · 技术社区  · 15 年前

    以下是我想做的:

    我有一个带有链接的页面。大多数的链接都有一个附加在网络上的功能 onclick 事件

    现在,我想为一些链接设置一个css类,然后每当单击其中一个链接时,我想执行某个函数——在它返回后,我想让链接执行附加到它的onclick函数。

    有没有办法做我想做的事?如果有什么不同,我会使用jQuery。

    下面是一个例子:

    $("#link").click(function1);
    $("#link").click(function2);
    $("#link").click(function(){
       firstFunctionToBeCalled(function (){
          // ok, now execute function1 and function2
       });
    }); // somehow this needs to be the first one that is called
    
    
    function firstFunctionToBeCalled(callback){
        // here some user input is expected so function1 and function2 must not get called
        callback();
    
    }
    

    所有这一切都是因为我被要求为许多按钮放置一些确认框(使用长方形),我真的不想查看每个按钮。

    4 回复  |  直到 15 年前
        1
  •  1
  •   Marc Gravell    13 年前

    如果我没弄错的话,这是你想做的事吗。。

    var originalEvent = page.onclick;   //your actual onclick method
    page.onclick = handleinLocal;       //overrides this with your locaMethod
    
    function handleinLocal()
    {     ...your code...     
       originalEvent (); 
     // invoke original handler
    }
    
        2
  •  0
  •   Fenton    15 年前

    我将使用jQuery的unbind删除任何现有事件,然后绑定一个函数,该函数将按照我想要的顺序编排我想要的事件。

    绑定和取消绑定都在jQuery上的jQuery文档中。像这样工作。。。

    $(".myClass").unbind("click"); // removes all clicks - you can also pass a specific function to unbind
    
    $(".myClass").click(function() {
        myFunctionA();
        myFunctionB($(this).html()); // example of obtaining something related to the referrer
    });
    
        3
  •  0
  •   kgiannakakis    15 年前

    使用mousedown或mouseup事件将是一个丑陋的黑客行为。这些将被称为 before the click event .

        4
  •  0
  •   phuzi    5 年前

    如果可以在其他处理程序之前添加事件处理程序,那么可以尝试使用jQuery的 stopImmediatePropagation