1

我被困在试图取消绑定并重新绑定点击事件。我想“保存”点击事件,取消绑定,然后用条件语句重新绑定。

我可以使用此处的信息来保存单击处理程序: jQuery find events handlers registered with an object

我使用的是旧版本的 jQuery (1.5),所以我使用的是 data("events") 方法。

至今...

var events = $('#myElement').data("events");

alert(events.click[0].handler);

$('#myElement').unbind('click');

现在它会提醒我处理函数,它看起来是正确的。我想向它添加东西,但我认为对于初学者来说,我会尝试重新绑定相同的点击事件。但是,我不确定如何正确重新绑定。我尝试过的事情:

$('#myElement').bind('click', null, events.click[0].handler); // gives 'click.0 is null or not an object

$('#myElement').bind('click', events.click[0].handler); // gives 'click.0 is null or not an object

$('#myElement').bind('click', null, events.click); // seems to have no effect

$('#myElement').bind('click', events.click); // seems to have no effect

所以我觉得我几乎拥有它,但我不知道从这里做什么。如何使用 events 变量重新绑定 click 事件?

感谢您的任何帮助。

4

1 回答 1

1

You can make use of the .die() method in jQuery (added in 1.4.1). Any handler that has been attached with .live() can be removed with .die().

Ref for .die() : http://api.jquery.com/die/
Ref for .live() : http://api.jquery.com/live/

HTML

<div id="myElement">Testing save event</div>

JavaScript

<script type="text/javascript">
    $(document).ready(function() {


     function ClickEventHandler()
     {
        alert('abc');
     }

     $('#myElement').live('click', ClickEventHandler);


     function GetClickEventHandler(selector)
     {
        for(var i = 0 ; i < $._data(document).events.live.length ; i++)
        {
            if( $._data(document).events.live[i].selector == selector )
            {
                return $._data(document).events.live[i].handler;
            }
        }   
        return null;
     }

     var myFn = GetClickEventHandler('#myElement');

     $('#myElement').die();


     $('#myElement').live('click', myFn );
    });
</script>

To see is the code actually work, you can try comment out $('#myElement').live('click', myFn ); and click the element, it should not alert. Then enable this back, it will alert.

Added jsfiddle example:
One is commented out : http://jsfiddle.net/9wbPH/1/
One is actual work: http://jsfiddle.net/9wbPH

于 2013-02-26T16:30:37.943 回答