如何运行更多ID的function?

当用户选中某些选项时,我想禁用表单中的上一个按钮。 因此,如果他选择ID 1 OR 2 OR 3,则必须禁用上一个按钮。

但是如果用户检查1而不是2 OR 3,则前一个按钮必须保持禁用状态。 如果他没有选择1 OR 2 OR 3,则必须启用前一个按钮。

我尝试了以下方法:

$.each(["1", "2", "3"], function(index, mainOption) { $('#option_' + mainOption).change(function() { if ($(this).prop('checked')) { $('#previous_button').prop('disabled', true); } else { $('#previous_button').prop('disabled', false); } }); }); 
  

相关的JS小提琴在这里

所以你看到取消选中其中一个启用按钮

我试过了,但这并没有完全符合我的要求,使用此按钮将在选中1或2或3时启用,取消选中其中一个将启用该按钮。 那不是我想要的。 如果选中其中一个选项,则前一个按钮必须保持禁用状态。 仅当未选中其中一个时,才必须启用该按钮。

您必须考虑所有复选框(此代码仍可以优化):

 let ids = ["1", "2", "3"]; $.each(ids, function( index, mainOption ) { $('#option_'+mainOption).change(function(){ if($(this).prop('checked')){ $('#previous_button').prop('disabled', true); } else { let cnt = 0; $.each(ids, function( index, mainOption ) { if ($('#option_'+mainOption).prop('checked')) { cnt++; } }) if (cnt === 0) { $('#previous_button').prop('disabled', false); } } }); }); 

您可以使用事件委派机制并在第一个共同祖先上注册侦听器,并将disabled属性应用于上一个按钮,无论是否已选中一个或多个复选框。

 // The function used to filter eligible checkboxes // to be passed to jQuery "filter" function below let myFilter = function (i, el) { // Only include checkboxes whose id matches the following pattern return /-[12]$/.test(el.id) } // Register click event on the first common ancestor $('form').on('click', function(e) { let $form = $(this), $target = $(e.target); // If a checkbox get clicked if ($target.is('input[type="checkbox"]')) { let shouldDisable = !!$form.find('input:checked').filter(myFilter).length; $form.find('button').prop('disabled', shouldDisable); } }); 
  

Select one or more items