如何覆盖 jquery 事件处理程序 [英] How to overwrite jquery event handlers

查看:21
本文介绍了如何覆盖 jquery 事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会尝试用一个简单的代码来解释这个问题.

I'll try to explain the problem with a simple code.

var fireClick = function() { alert('Wuala!!!') };

$('#clickme').click(fireclick);
$('#clickme').click(fireclick);

所以现在它显然会提醒 2 次,但我只需要提醒一次.尝试了很多方法,但没有结果.

So now it will obviously alert 2 times but i need it alert only once. Tried so many ways, but no result.

谢谢.

推荐答案

从 jQuery 1.7 开始,您应该使用 off 删除事件处理程序并 on 添加它们,尽管您仍然可以使用 click 简写.

As of jQuery 1.7 you should be using off to remove event handlers and on to add them, though you can still use the click shorthand.

$('#clickme').off('click').on('click', fireclick);
$('#clickme').off().on('click', fireclick);

原答案:

如果要替换所有点击处理程序,请先调用 unbind 而不使用函数参数.如果要替换所有事件处理程序,请不要指定事件类型.

If you want to replace all click handlers, call unbind first without a function argument. If you want to replace all event handlers, don't specify the event type.

$('#clickme').unbind('click').click(fireclick);
$('#clickme').unbind().click(fireclick);

这篇关于如何覆盖 jquery 事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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