2010-10-19 92 views
1

我有幾個複選框。如果用戶檢查他們中的任何一個,我必須看看他們是否被允許這樣做,如果沒有,通知他們並取消選中。但是,這會讓我陷入循環,因爲它會再次觸發更改!我怎麼能過來呢?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(); 
     } 

}); 

我無法解除綁定,然後重新綁定更改事件,因爲還有一個插件依賴於此事件。

我還有其他選擇嗎?我可以附加一個函數調用到每個複選框,但我希望有一些更優雅,如果沒有,我會默認這個。

感謝所有的幫助

回答

2

您可以使用.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

0

最簡單的變化是這樣的:

var inClickHandler = false; 

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

    // Do your stuff. 
} 
0

你爲什麼叫這條線? $('#other_stages :checkbox:not(#section_2_active, #co_t)').change();據我所見,你不需要這個,它不會循環。該複選框仍然會檢查,除非您使用event.preventDefault();.attr('checked',false);不會觸發更改,可能是因爲您遇到了問題。