JQuery更改事件循环

问题描述:

我有几个复选框。如果用户检查他们中的任何一个,我必须看看他们是否被允许这样做,如果没有,通知他们并取消选中。但是,这会让我陷入循环,因为它会再次触发更改!我怎么能过来呢?JQuery更改事件循环

$('#step_1, #step_2, #step_3, #step_4').change(function(event) { 
     if(!$('#section_2_active').attr('checked')){ 
      alert('You can not select output options when "Create Output" has not been selected.'); 

      $(this).attr('checked', false); 

      $('#other_stages :checkbox:not(#section_2_active, #co_t)').change(); 
     } 

}); 

我无法解除绑定,然后重新绑定更改事件,因为还有一个插件依赖于此事件。

我还有其他选择吗?我可以附加一个函数调用到每个复选框,但我希望有一些更优雅,如果没有,我会默认这个。

感谢所有的帮助

您可以使用.trigger()传递到您的处理额外的参数,我们将使用loop。如果是false,不要再运行其它元素触发,比如:

$('#step_1, #step_2, #step_3, #step_4').change(function(event, loop) { 
    if(!$('#section_2_active').attr('checked')){ 
    alert('You can not select output options when "Create Output" has not been selected.'); 
    $(this).attr('checked', false); 
    if(loop !== false) 
     $('#other_stages :checkbox:not(#section_2_active, #co_t)').trigger('change', false); 
    } 
}); 
+0

完美答案,谢谢尼克。 – Abs 2010-10-19 15:42:19

最简单的变化是这样的:

var inClickHandler = false; 

function OnChecked(evt) { 
    if (inClickHandler) { 
    inClickHandler = false; 
    return; 
    } 
    inClickHandler = true; 

    // Do your stuff. 
} 

你为什么叫这条线? $('#other_stages :checkbox:not(#section_2_active, #co_t)').change();据我所见,你不需要这个,它不会循环。该复选框仍然会检查,除非您使用event.preventDefault();.attr('checked',false);不会触发更改,可能是因为您遇到了问题。