简体   繁体   中英

Grouping similar jQuery functions

Is there a way to group the following functions into one?

$('#box_1 input:checkbox').click(function(){
var $inputs = $('#box_1 input:checkbox')
    if($(this).is(':checked')){
       $inputs.not(this).prop('disabled',true); 
    }else{
       $inputs.prop('disabled',false);
    }
});
$('#box_2 input:checkbox').click(function(){
var $inputs = $('#box_2 input:checkbox')
    if($(this).is(':checked')){
       $inputs.not(this).prop('disabled',true); 
    }else{
       $inputs.prop('disabled',false);
    }
});

There are more of the box_id's. Would be great to have a simpler solution than writing 2 km of code

Thanks a lot in advance for helping

Put a common class on all your #box_X elements and use that for targeting

$('.common-class').on('click', 'input:checkbox', function(){

    var $inputs = $(this).closest('.common-class').find('input:checkbox');

        if (this.checked) {
           $inputs.not(this).prop('disabled',true); 
        } else {
           $inputs.prop('disabled',false);
        }
});

Approach looping over all the outer boxes first

$('[id^=box_]').each(function(){    
   var $inputs=$(this).find(':checkbox').change(function(){
        $inputs.not(this).prop('disabled', this.checked);
   });
});

ID as attribute selector is a bit ugly, prefer using common class instead

Give a common class to your box ID's - say "box"

$(".box :checkbox").click(function() {
    //reference the current clicked checkbox with 'this'
    //this.id will give the ID of the clicked box
    var $inputs = $(this).siblings("checkbox");
    if (this.checked) {
        $inputs.prop("disabled", true);
        //do checked
    } else {
        //not checked
        $inputs.prop("disabled", false);
    }
});

if nothing else, you could put it in a for loop and generate your selector dynamically.

for (var i=0; i<n; i++){
    $('#box_' + i + ' input:checkbox').click(function(){
    var $inputs = $('#box_' + i + ' input:checkbox')
        if($(this).is(':checked')){
           $inputs.not(this).prop('disabled',true); 
        }else{
           $inputs.prop('disabled',false);
        }
    });
}

A class selector would be more elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM