簡體   English   中英

如何使此重復代碼更有效:jquery

[英]How to make this repeating code more efficient: jquery

    jQuery('.checkbox1').click(function(){
        jQuery(this).parent().toggleClass('active')
    });
    jQuery('.checkbox2').click(function(){
        jQuery(this).parent().toggleClass('active')
    });
    jQuery('.checkbox3').click(function(){
        jQuery(this).parent().toggleClass('active')
    });
    jQuery('.checkbox4').click(function(){
        jQuery(this).parent().toggleClass('active')
    });

我對所有四個都運行相同的功能。 我可以使用.each()類的東西嗎? 有人可以告訴我如何壓縮此代碼嗎?

謝謝

您可以簡單地做到這一點:

jQuery('.checkbox1, .checkbox2, .checkbox3, .checkbox4').click(function(){
    jQuery(this).parent().toggleClass('active')
});

或者您可以創建一個新類,說出checkbox以應用到所有復選框,然后使用以下方法:

jQuery('.checkbox').click(function(){
    jQuery(this).parent().toggleClass('active')
});

最好的方法是在所有元素中添加一個附加的類復選框,然后使用

<input type="checkbox" class="checkbox checkbox1" />
<input type="checkbox" class="checkbox checkbox2" />
<input type="checkbox" class="checkbox checkbox3" />
<input type="checkbox" class="checkbox checkbox4" />

然后

jQuery('.checkbox').click(function(){
    jQuery(this).parent().toggleClass('active')
});

如果您不能這樣做,則使用多個選擇器

jQuery('.checkbox1, .checkbox2, .checkbox2, .checkbox4').click(function(){
    jQuery(this).parent().toggleClass('active')
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM