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

如何在Alpine JS中根据单选框选中状态显示/隐藏对应Div区块

单选切换对应区块显隐的Alpine JS实现

你原有jQuery的交互逻辑可以完全通过Alpine的状态驱动能力改写,不需要手动操作DOM、绑定事件、遍历元素,代码更简洁,最终效果和原逻辑完全一致。

完整实现代码

<!-- 外层包裹Alpine组件作用域,定义存储选中值的状态 -->
<div x-data="{ selectedVal: '' }">
  <h3> Who was involved in this incident? </h3>

  <p>
    <label>
      <input name="Victim" type="radio" value="Guest" required x-model="selectedVal">
      Guest 
    </label>
  </p>
  <div id="Guest" class="desc" x-show="selectedVal === 'Guest'">
      <p><strong>Guest</strong> questions here ...</p>
  </div>

  <p>
    <label>
      <input name="Victim" type="radio" value="Employee" x-model="selectedVal"> 
      Employee 
    </label>
  </p>
  <div id="Employee" class="desc" x-show="selectedVal === 'Employee'">
      <p><strong>Employee</strong> questions here ...</p>
  </div>
    
  <p>
    <label>
      <input name="Victim" type="radio" value="Vendor" x-model="selectedVal"> 
      Vendor
    </label>
  </p>
  <div id="Vendor" class="desc" x-show="selectedVal === 'Vendor'">
    <p><strong>Vendor</strong> questions here ...</p>
  </div>
</div>

注:使用前请确保页面已正确加载Alpine JS运行环境。

逻辑对应说明

  • 初始状态selectedVal为空字符串,所有.desc区块的显示判断条件不成立,默认全部隐藏,和原jQuery页面加载后隐藏所有desc区块的逻辑完全一致
  • 所有单选框通过x-model绑定到selectedVal状态,点击单选时Alpine会自动把当前选中的value同步到状态中,不需要手动编写click事件监听逻辑
  • 每个.desc区块通过x-show指令判断当前选中值是否和自身匹配,匹配则自动显示,不匹配则自动隐藏,不需要手动遍历所有desc区块执行隐藏、再查找对应id区块显示的DOM操作
  • 如果后续需要新增name以Victim结尾的单选选项,只需要给新的单选框绑定同一个x-model,给对应的desc区块写好匹配的x-show判断条件即可,不需要额外修改JS逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 21:51:19