jQuery触发器-'更改'功能 [英] jquery trigger - 'change' function

查看:101
本文介绍了jQuery触发器-'更改'功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"pick_up_point"的单选按钮集,并且我有一个更改处理程序来检测已选中的单选按钮.在变更处理程序中,我调用了一个"clearFields()"函数,该函数基本上清除了输入字段.

I have a radio button set called "pick_up_point" and I have a change handler to detect the radio button that is checked. In the change handler I call a function "clearFields()" which basically clears out the input fields.

function clearFields()
{
 $("#Enquiry_start_point").val("");
 $("#Enquiry_start_town").val("");
 $("#Enquiry_start_postcode").val("");
}

$("input[name='pick_up_point']").change(function()
{
 if($("input[name='pick_up_point']:checked").val() == "pick_up_airport")
 {
  $("#pick_up_airport_div").slideDown();
  $("#start_point_div").hide();
  clearFields();
 }
});

我还有一个触发器,如果​​由于验证错误而重新显示该表单,则会保留该视图.

I also have a trigger which will retain the view if the form is redisplayed due to a validation error.

$('input[name=\'pick_up_point\']').trigger('change');

现在,当我发布表单时,触发器将运行并调用更改处理程序,该处理程序当然将运行clearFields()函数.那么我该如何解决呢?我不希望在重新显示表单时清除字段.

Now when I post the form the trigger is run and it calls the change handler, which of course runs the clearFields() function. So how can I get around this? I don't want the fields being cleared when the form is re-displayed.

推荐答案

尝试使用自定义事件处理程序,如下所示:

Try using a custom event handler, like so:

$("input[name='pick_up_point']").change(function()
{
    $(this).trigger("displayForm");
    clearForm();
});

$("input[name='pick_up_point']").bind("displayForm", function() {
 if($("input[name='pick_up_point']:checked").val() == "pick_up_airport")
 {
  $("#pick_up_airport_div").slideDown();
  $("#start_point_div").hide();
 }
});

因此,无需触发更改事件,而是触发定制的displayForm处理程序,如下所示:

So instead of triggering the change event, trigger the custom displayForm handler, like this:

$('input[name=\'pick_up_point\']').trigger('displayForm');

现在,当触发change时,它可以按预期工作,但是对于在不清除输入字段的情况下显示表单的特殊情况下,您只需触发新的自定义事件处理程序即可.

And now, when change is triggered, it works as expected, but for the special case of displaying the form without clearing the input fields, you can simply trigger your new custom event handler.

这篇关于jQuery触发器-'更改'功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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