简体   繁体   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')
    });

I run the same function on all 4 of them. 我对所有四个都运行相同的功能。 Can i use something like .each() ? 我可以使用.each()类的东西吗? Can someone show me how to condense this code? 有人可以告诉我如何压缩此代码吗?

Thanks 谢谢

You could simply do this: 您可以简单地做到这一点:

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

Or you could create a new class, say checkbox to apply to all of your checkboxes, then use this: 或者您可以创建一个新类,说出checkbox以应用到所有复选框,然后使用以下方法:

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

The best way could be to add an additional class checkbox to all the elements then use 最好的方法是在所有元素中添加一个附加的类复选框,然后使用

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

then 然后

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

if you can't do that then use multiple selector 如果您不能这样做,则使用多个选择器

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