保留当前点击事件jquery

Preserving current click event jquery

本文关键字:事件 jquery 保留      更新时间:2024-02-13

我需要临时更改元素的点击事件,如下所示:

var originalEvent = '';
$("#helpMode").click(function (e) {
      originalEvent = $("#element").getCurrentClickEventHandler();
      $("#element").click(function (e) {
          //Do something else
      });
});
//Later in the code
$("#helpModeOff").click(function (e) {
      $("#element").click(originalEvent);
});

如何将作为事件处理程序的当前函数存储在全局变量中以供以后重用?

编辑:以下是我想做的:

var evnt = '';
$("#helpTool").click(function (e) {
if(!this.isOn){
evnt = $("#Browse").data('events').click;
$("#ele").unbind('click');
$("#ele").click(function (e) {
    alert('dd');
});
this.isOn=true;
}else{
    this.isOn = false;
    alert('off');
    $("#ele").unblind('click');
    $("#ele").click(evnt);
}
});

给你,找到了:

现在使用e.srcElement.id,您可以获得HelpMode或HelpModeOff,然后可以打开/关闭您的帮助内容!

http://jsfiddle.net/zcDQ9/1/

var originalEvent = '';
$('#element').on('yourCustomEvent', function (e) {
   // do stuff
   alert(originalEvent);
   $(this).toggleClass('toggleThing');
   //test for helpMode or helpModeOff here now...
});
$("#helpMode").on('click', function (e) {
    originalEvent = e.srcElement.id;
    $("#element").trigger('yourCustomEvent');
});

//Later in the code
$("#helpModeOff").on('click', function (e) {
   originalEvent = e.srcElement.id;
   $("#element").trigger('yourCustomEvent');
});​

好的。在jQuery 1.7中,我想它有点不同。

//get the handler from data('events')
$.each($("#element").data("events"), function(i, event) {
    if (i === "click") {
        $.each(event, function(j, h) {
            alert(h.handler);
        });
    }   
});

http://jsfiddle.net/yQwZU/

这是参考资料。

不确定以下内容是否适用于1.7。

originalEvent = $('#element').data('events').click;

jQuery将所有处理程序存储在CCD_ 1中。请参阅此处了解有关data('events')的更多信息。

就我个人而言,我认为我应该避免手动绑定和取消绑定处理程序。

另一种方法是将单击事件绑定到类,然后在切换到帮助模式或从帮助模式切换时,只需要在适当的元素中添加和删除类。

这里有一个jsfiddle来说明我的意思。

切换到帮助模式和从帮助模式切换只需要添加删除类:

$('#btnhelpmode').click(function(){
    if(!helpMode){
     helpMode = true;   
     $('.normalmode').addClass('helpmode').removeClass('normalmode');
     $(this).val('Switch to normal mode...');                            
    }else{
     helpMode = false;   
     $('.helpmode').addClass('normalmode').removeClass('helpmode');              
     $(this).val('Switch to help mode...');                                        
    }        
});

您只需创建所需的处理程序,将它们绑定到适当的类:

$('#pagecontent').on('click', '#element1.normalmode', function(){        
   alert('element1 normal mode'); 
});
$('#pagecontent').on('click', '#element1.helpmode', function(){        
   alert('element1 help mode'); 
});
$('#pagecontent').on('click', '#element2.normalmode', function(){        
   alert('element2 normal mode'); 
});
$('#pagecontent').on('click', '#element2.helpmode', function(){        
   alert('element2 help mode'); 
});