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

如何用jQuery限制高亮复选框(li)的数量不超过2个?

解决最多同时高亮2个复选框按钮的问题

嘿,我来帮你搞定这个限制最多2个高亮按钮的需求~你现在的代码已经实现了点击切换高亮,但没有数量限制,咱们只要在点击事件里加个判断逻辑就行:

修改后的JavaScript代码

$("#answers-type1 li").click(function() {
  const $currentLi = $(this);
  // 统计当前已经高亮(带place类)的li数量
  const highlightedCount = $("#answers-type1 li.place").length;
  
  // 如果当前li已经是高亮状态,直接取消(保持toggle的原有逻辑)
  if ($currentLi.hasClass("place")) {
    $currentLi.toggleClass("place");
    // 同步隐藏复选框的选中状态,确保表单数据正确
    $currentLi.find("input[type='checkbox']").prop("checked", false);
  } else {
    // 还没到2个高亮,才允许添加高亮
    if (highlightedCount < 2) {
      $currentLi.toggleClass("place");
      $currentLi.find("input[type='checkbox']").prop("checked", true);
    } else {
      // 可选:给用户提示不能选更多了
      alert("最多只能选择2个选项哦!");
    }
  }
});

代码说明

  • 首先我们先获取当前点击的li元素,以及已经高亮的li数量
  • 如果点击的li已经是高亮状态,直接取消高亮,同时把对应的隐藏复选框设为未选中(因为用户看不到复选框,得保证样式和实际表单状态一致)
  • 如果点击的li未高亮,先检查当前高亮数量是否小于2:
    • 是的话,添加高亮类,同时把复选框设为选中
    • 不是的话,弹出提示告诉用户最多选2个

你的原有代码(无需修改)

CSS

.place { background-color: #27B249 !important; }

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
<ul id="answers-type1" class="myclass" style="list-style: none;padding-right: 10px;padding-left: 10px;"> 
  <li class="module" style="background: #668693;" value="Listol"><input name="listol" type="checkbox" value="Listol" class="number" style="display: none;"><span>Listol</span></li> 
  <li class="module" style="background: #668693;" value="Synaptal"><input name="synaptal" type="checkbox" value="Synaptal" class="number" style="display: none;"><span>Synaptal</span></li> 
  <li class="module" style="background: #668693;" value="Synaptal"><input name="focus_formula" type="checkbox" value="Focus Formula" class="number" style="display: none;"><span>Focus Formula</span></li> 
  <li class="module" style="background: #668693;" value="Bright Spark"><input name="bright_spark" type="checkbox" class="number" value="Bright Spark" style="display: none;"><span>Bright Spark</span></li> 
  <li class="module" style="background: #668693;" value="Triple Complex"><input name="triple_complex" type="checkbox" class="number" value="Triple Complex" style="display: none;"><span>Triple Complex</span></li> 
</ul>

这样修改后,就能完美实现同一时间最多2个按钮高亮的需求啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:23:55