繁体   English   中英

分组相似的jQuery函数

[英]Grouping similar jQuery functions

有没有一种方法可以将以下功能组合在一起?

$('#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);
    }
});

还有更多的box_id。 有一个比编写2 km的代码更简单的解决方案的绝佳选择

在此先感谢您的帮助

在所有#box_X元素上放置一个通用类,并将其用于定位

$('.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);
        }
});

首先遍历所有外部框

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

ID作为属性选择器有点难看,建议改用普通类

给您的box ID分配一个通用类-说“ 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);
    }
});

如果没有其他问题,则可以将其放在for loop并动态生成选择器。

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);
        }
    });
}

类选择器会更优雅。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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