jquery如何取消一个函数 [英] Jquery how to untrigger a function

查看:157
本文介绍了jquery如何取消一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个动态表单。我有一个下拉列表,当用户进行选择时,会查询数据库以查看该项目是否需要隐私。如果没有,则会将其他字段添加到表单中。此外,还会触发一个邮政编码查询ajax功能,但只有在该项目不是私人信息时才会触发。



这一切正常,直到用户改变主意。 ..



这是我从下拉列表中选择一个项目时运行的代码的相关部分;

 成功:函数(响应){
if(response ==='1'){
//为需要隐私的项目做些事
//不触发zip_check函数
} else if(response ==='0'){
//为公共项目添加东西+
$('#zip-code' ).keyup(zip_check); //触发一个函数来检查邮政编码


code $ $ $ $ $ $如预期的那样,直到用户选择非私人项目,然后改变他们的想法并选择私人项目,在这种情况下,即使它现在不应该被触发,zip_check功能仍将运行。我在哪里错了?

解决方案

我认为您正在寻找 off (在(response === 1){} / code>):

  $('#zip-code')。off('keyup',zip_check) ; 

这样您可以从click事件中移除该函数。如果你想删除所有事件,只需使用

  $('#zip-code')。 

如果您想关闭所有活动:

  $( '#拉链码')关闭()。 

.off()是首选的方法通过 .unbind() .on() 用于 .bind()


I'm creating a dynamic form. I have a dropdown list which when the user makes a selection, the database is queried to see if the item required privacy or not. If it doesn't then additional fields are added to the form. Also a zip code lookup ajax function is triggered, but should only be triggered if the item is not private.

This is all working fine, until a user changes their mind...

Here is the relevant part of my code that runs when ever an item is selected from the dropdown;

success:function(response){
    if(response === '1'){
        // do stuff for item that requires privacy
        // do NOT trigger zip_check function
    }else if(response === '0'){
        // do stuff for item that is public +
        $('#zip-code').keyup(zip_check); // triggers a function to check zip code
    }
}

This works as expected until a user selects a non private item then changes their mind and selects a private item in which case the zip_check function will still run even though it now shouldn't be getting triggered. Where am I going wrong?

解决方案

I think you are looking for off (add this in the (response===1){} ):

$('#zip-code').off('keyup', zip_check);

This way you remove that function from the click event. If you want all events removed, just use

$('#zip-code').off('keyup');

If you want all events off:

$('#zip-code').off();

.off() is the prefered method over .unbind(), and .on() for .bind()

这篇关于jquery如何取消一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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