Jquery复选框影响一个项目而不是所有项目

时间:2016-11-16 17:02:29

标签: javascript jquery html css checkbox

我想知道是否有人可以帮助我,我有一系列复选框,点击后更改div背景,激活2个输入并添加勾选图标。我的问题是,当选中一个复选框时,类.TickIco会显示所有内容,.disableToggle

也是如此。

我如何才能获得它,以便一次只影响一个.checkBG而不是所有这些?

希望这个JSFiddle有助于解释我的意思。

https://jsfiddle.net/jayjay89/xfg96we5/

感谢

$(".checkBG").click(function () {
var checked = $(this).is(':checked');
var location = $(this).parent().parent().parent();
if (checked) {
    $(this).parent().parent().parent().addClass("activeformBlock");
    $(".tickIco").show();
    $(".disabletoggle").removeAttr("disabled");


} else {
    $(this).parent().parent().parent().removeClass("activeformBlock");
    $(".tickIco").hide();
    $(".disabletoggle").attr('disabled', 'disabled');
}

});

感谢

2 个答案:

答案 0 :(得分:2)

您可以使用查看选择器的上下文。

您已经拥有了位置变量,它是您的某个行

的父上下文
$(".checkBG").click(function () {
    var checked = $(this).is(':checked');
    var location = $(this).parent().parent().parent();
    if (checked) {
        $(this,location).parent().parent().parent().addClass("activeformBlock");
        $(".tickIco",location).show();
        $(".disabletoggle",location).removeAttr("disabled");


    } else {
        $(this,location).parent().parent().parent().removeClass("activeformBlock");
        $(".tickIco",location).hide();
        $(".disabletoggle",location).attr('disabled', 'disabled');
    }
});

答案 1 :(得分:0)

您的问题在于您选择.tickIco.disabletoggle元素的方式:

$(".tickIco").show();
$(".disabletoggle").removeAttr("disabled");

这些jquery调用使用的选择器匹配.tickIco.disabletoggle所有类。

脏解(使用.find()找到具有匹配类的父元素):

$(this).parent().parent().parent().find(".tickIco").show();
$(this).parent().parent().parent().find('.disabletoggle').removeAttr("disabled")

更好的解决方案:

jQuery selecter将您选择的上下文作为第二个参数,以便您可以:

var context = $(this).parent().parent().parent();
$(".tickIco", context).show();
$('.disabletoggle', context).removeAttr("disabled")
相关问题