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

如何用JavaScript实现同一时间仅一个tab的aria-selected属性为true

解决方案

现有代码问题

  • 逻辑存在错误:判断分支内统一将属性设为false,永远无法触发选中状态
  • 操作属性不匹配:需要控制的是WAI标准的aria-selected属性,而非自定义的data-selected
  • 未处理同组元素:点击当前按钮时没有重置同标签组其他按钮的选中状态
  • 选择器范围过宽:直接选中页面所有button元素,会干扰其他功能的按钮逻辑

修复后完整代码

<div role="tablist" data-value-id="option_188647_7a6a36de-cae4-426e-848e-9770e831ab53" class="button-value-div">
  <button role="tab" type="button" data-value-id="value_188647_7a6a36de-cae4-426e-848e-9770e831ab53_93ffc302-3c0a-4c2b-885f-8e893241802c" id="black" class="beside-image test-sin" data-default="1">
  </button>
  <button aria-selected="false" role="tab" type="button" data-value-id="value_188647_7a6a36de-cae4-426e-848e-9770e831ab53_3fa2c66a-22ce-42df-b978-61eaba10131c" id="white" class="beside-image test-sin">
  </button>
</div>

<script>
$(document).ready(function(){
  // 限定选择器仅作用于当前标签组的tab按钮,避免影响其他页面元素
  const $tabButtons = $('.button-value-div button[role="tab"]');
  // 初始化所有按钮为未选中状态
  $tabButtons.attr('aria-selected', 'false');
  // 激活默认选中项(带data-default="1"标记的按钮)
  $tabButtons.filter('[data-default="1"]').attr('aria-selected', 'true');

  // 绑定点击切换逻辑
  $tabButtons.on('click', function() {
    // 先重置同组所有按钮为未选中
    $tabButtons.attr('aria-selected', 'false');
    // 仅将当前点击的按钮设为选中
    $(this).attr('aria-selected', 'true');
  });
});
</script>

样式适配提示

如果需要同步修改选中按钮的样式,可以直接通过属性选择器写CSS:

.button-value-div button[aria-selected="true"] {
  /* 自定义选中状态样式,示例如下 */
  border-color: #222;
  background: #222;
  color: #fff;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:24:03