用jQuery重新绑定DOM事件 [英] Rebind DOM Event with jQuery

查看:103
本文介绍了用jQuery重新绑定DOM事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这纯粹是一个理论问题,因此我不寻求替代解决方案.

是否可以通过某种方式使默认处理程序执行类似的操作

var defaultHandler = $("#test").click;
$('#test').unbind('click');
$('#test').bind('click', defaultHandler);

解决方案

您可以访问.data('events')对象,该对象用于存储所有事件处理程序信息:

$(document).ready(function() {
    var $test = $('#test');

    $test.bind('click', function() {
        alert('default handler');
    });   

    var storedClick = $test.data('events').click[0].handler;

    $test.unbind('click');

    $('#restore').click(function() {
        $test.bind('click', storedClick);
    });
});

查看实际操作: http://www.jsfiddle.net/76GPF/

请记住,events object持有Arrays,因此在现实世界中,您应该存储完整的阵列信息.我只是在此示例中存储了第一个处理程序.

This is purely a theoretical question so I'm not looking for alternative solutions.

Is there some way of getting the default handler to do something like this

var defaultHandler = $("#test").click;
$('#test').unbind('click');
$('#test').bind('click', defaultHandler);

解决方案

You can access the .data('events') object, which is used to store all event handler information:

$(document).ready(function() {
    var $test = $('#test');

    $test.bind('click', function() {
        alert('default handler');
    });   

    var storedClick = $test.data('events').click[0].handler;

    $test.unbind('click');

    $('#restore').click(function() {
        $test.bind('click', storedClick);
    });
});

See this in action: http://www.jsfiddle.net/76GPF/

Remember, the events object is holding Arrays, so in the real world you should store the complete array information. I just stored the very first handler in this example.

这篇关于用jQuery重新绑定DOM事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆