尝试创建一个复选框来比较元素

Trying to create a checkbox for comparing elements

本文关键字:复选框 一个 比较 元素 创建      更新时间:2023-09-26

到目前为止,当复选框被选中时,我设法显示/隐藏按钮,但它正在检查所有我不想要的复选框。

我的目标是选中不同的复选框,而不是同时选中所有的复选框。

编辑:也可以计算已经检查了多少个元素。

http://jsfiddle.net/bLd0gaxy/1/

<input type="checkbox" class="compare" name="compare">
<label for="compare" class="compare-label ml-10"> Compare</label>
<!-- <div class="compare-btn"></div> -->
<button class="compare-btn ml-10" style="display: none;">Compare</button>
<input type="checkbox" class="compare" name="compare">
<label for="compare" class="compare-label ml-10"> Compare 2</label>
<!-- <div class="compare-btn"></div> -->
<button class="compare-btn ml-10" style="display: none;">Compare</button>
        $('.compare').click(function() {
        if($('.compare').is(':checked')){
            $('.compare-label').hide();
            $('.compare-btn').show();            
        } else{
            $('.compare-label').show();
            $('.compare-btn').hide();
        }
    });

您必须使用.prop("checked")才能获得选中状态(http://api.jquery.com/prop/)。下面是您的工作示例:http://jsfiddle.net/infous/bLd0gaxy/3/

您需要使用this来处理最接近的元素:

$('.compare').change(function() {
    if (this.checked) {
        $(this).next("label").hide();
        $(this).nextUntil("button").show();
    } else {
        $(this).next("label").show();
        $(this).nextUntil("button").hide();
    }
    var totalChecked = $(".compare:checked").length;
});

同时,使用复选框的change事件