簡體   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