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

jQuery如何使用变量ID隐藏除指定元素外的所有元素

核心实现逻辑

你需要的动态ID排除写法只需要把动态年份变量拼接到jQuery选择器中即可,完整修改方案如下:

1. 修改点说明

  • PHP端复选框默认选中逻辑从固定判断2021改为判断动态当前年,避免每年手动修改
  • 将PHP生成的当前年输出为JS可读取的变量,替换固定值的隐藏逻辑
  • 移除重复引入的jQuery版本,避免版本冲突

2. 完整修改后代码

<html>
<head>
    <title>Purchase</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <style type="text/css">
        .selectt {
            color: #fff;
            padding: 30px;
            display: block;
            margin-top: 30px;
            width: 60%;
            background: grey;
        }
    </style>
</head>
<body>
<center>
<table>
<?php 
// 当前年定义提到循环外,避免重复计算
$currentYear = date("Y");
// 循环上限设为当前年+1,不用每年手动调整年份范围
for ($i = 2018; $i <= $currentYear + 1; $i++) {
?>
<tr>
 <td>
    <input type="checkbox" name="Checkbox" value="<?php echo $i; ?>" <?php if($i == $currentYear) { echo 'checked'; } ?> >
    <?php echo $i; ?>
     <div class="<?php echo $i; ?> selectt" id="<?php echo $i; ?>" >
          This data belongs to this year
    </div>
 </td>
</tr>
<?php } ?>
</table>
<script type="text/javascript">
// 获取PHP输出的动态当前年
const currentYear = <?php echo $currentYear; ?>;
// 动态拼接选择器,隐藏所有非当前年的区块
$('div:not(#' + currentYear + ')').hide();

$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        const inputValue = $(this).val();
        $("." + inputValue).toggle();
    });
});
</script>
</center>
</body>
</html>

3. 效果说明

  • 页面加载后默认仅选中并展示当年年份的数据
  • 勾选其他年份复选框,对应年份的数据区块自动显示
  • 取消勾选对应年份复选框,对应数据区块自动隐藏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:09:03