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

如何在ObservableHQ中获取radio单选框的选项标签label

实现方法

你可以通过以下两种方式获取选中项对应的label文本:

方法1:抽离配置项后匹配(推荐)

首先把radio的options配置抽成独立的可复用变量,之后用选中的value去遍历匹配对应label即可,示例代码如下:

// 先抽离options为独立变量
const classificationOptions = [
  { label: "体重过轻", value: "Underweight" },
  { label: "健康体重", value: "Normal" },
  { label: "超重", value: "Overweight" },
  { label: "肥胖", value: "Obese" }
]

viewof classification = radio({
  options: classificationOptions,
  value: "Underweight"
})

// 封装获取对应label的方法,直接调用即可
const getClassificationLabel = (val) => {
  return classificationOptions.find(item => item.value === val)?.label || ''
}

当你选中健康体重选项时,调用getClassificationLabel(classification)就会直接返回对应的标签文本。

方法2:直接读取radio组件DOM元素的选中项文本

如果不想改动原有配置,也可以通过DOM操作获取选中项的label:

// 替换选择器为你实际页面中radio组件对应的DOM选择器即可
const radioDom = document.querySelector('.your-radio-class')
const selectedLabel = radioDom.querySelector('input:checked + label').textContent

注意:方法2依赖组件的DOM结构,若组件后续更新结构可能会失效,更推荐用方法1的映射逻辑实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:15:05