You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据值隐藏Checkbox标签?实现跨区块互斥显示

问题描述

两段结构相似的标签代码,仅label类名(chkpositive、chknegative)和input的name属性不同,用于影片选择的标签展示。需求:

  • 点击chkpositive区块的复选框时,隐藏chknegative区块中值相同的标签
  • 点击chknegative区块的复选框时,隐藏chkpositive区块中值相同的标签
  • 可使用toggle方法实现

尝试的jQuery代码未生效,寻求可行方案。


原HTML代码

chkpositive 标签结构

<label class="checkbox-body chkpositive tags-block mb-5">
  <input class="checkbox" type="checkbox" value="{{$tag->id}}" name="tags[]">
  <div id="checkbox" class="checkbox-block"></div>
  <p class="constructor_checkbox-text">{{$tag->name}} ({{$tag->films->count()}})</p>
</label>

chknegative 标签结构

<label class="checkbox-body chknegative tags-block mb-5" value="{{$tag->id}}">
  <input class="checkbox" type="checkbox" value="{{$tag->id}}" name="notags[]" id="chknegative">
  <div id="checkbox" class="checkbox-block"></div>
  <p class="constructor_checkbox-text">{{$tag->name}}</p>
</label>

尝试的jQuery代码(未生效)

$(function() {
    $(".chkpositive input").click(function(event) {
        var x = $(this).is(':checked').value;
        if (x == true) {
            $(this).value.(".chknegative").hide();
        } else {
            $(this).value.(".chknegative").show();
        }
    });
  });

$(function() {
    $(".chknegative input").click(function(event) {
        var x = $(this).is(':checked').value;
        if (x == true) {
            $(this).value.(".chkpositive ").hide();
        } else {
            $(this).value.(".chkpositive ").show();
        }
    });
  });

原代码错误点

  1. $(this).is(':checked').value写法错误:is(':checked')返回布尔值,没有.value属性,需分开获取选中状态和值
  2. $(this).value.(".chknegative")语法错误:jQuery对象没有.value属性,获取值要用.val(),且选择器需精准定位对应值的标签

可行解决方案

以下代码可实现需求,监听复选框点击事件,根据选中状态切换对应值的标签显示/隐藏:

$(function() {
    // 处理chkpositive区块复选框点击
    $(".chkpositive input").on('click', function() {
        const tagValue = $(this).val();
        // 定位chknegative中对应值的label,切换显示状态
        $(`.chknegative input[value="${tagValue}"]`).closest('label').toggle(!$(this).is(':checked'));
    });

    // 处理chknegative区块复选框点击
    $(".chknegative input").on('click', function() {
        const tagValue = $(this).val();
        // 定位chkpositive中对应值的label,切换显示状态
        $(`.chkpositive input[value="${tagValue}"]`).closest('label').toggle(!$(this).is(':checked'));
    });
});

代码说明

  • 用.on('click')绑定事件,比click()更灵活
  • $(this).val()获取当前复选框的value值
  • $(.xxx input[value="${tagValue}"])精准定位同值的复选框
  • .closest('label')找到复选框所在的父级label标签(需隐藏整个标签区块)
  • toggle(!$(this).is(':checked')):选中复选框时隐藏对应标签,取消选中时显示对应标签

内容的提问来源于stack exchange,提问作者uladzimir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:45:39