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

如何在select的onchange事件中获取选中项的文本内容?

解决Select选中项文本获取及元素更新问题

嘿,我来帮你搞定这个小问题!你已经能通过this.value拿到选中值,但获取文本时踩坑了对吧?其实只要正确定位到选中的<option>元素,就能轻松拿到它的文本内容,再更新到.title元素里就好啦。

这里给你两种实用方案:

方案一:原生JavaScript方式

利用selectedIndex属性拿到选中项的索引,再通过options集合定位到对应option并获取文本:

$('select[name="ceremony"]').on('change', function(){
    // 获取选中项的文本内容
    const selectedText = this.options[this.selectedIndex].text;
    // 将文本更新到目标元素中
    $('.title').html(selectedText);
});

方案二:jQuery简化方式

直接用jQuery选择器定位当前select下的选中option,写法更简洁:

$('select[name="ceremony"]').on('change', function(){
    // 获取选中项的文本内容
    const selectedText = $('option:selected', this).text();
    // 将文本更新到目标元素中
    $('.title').html(selectedText);
});

为啥之前的this.options方法无效?

大概率是你没通过selectedIndex定位到具体的选中项——this.options是一个元素集合,直接调用text肯定拿不到内容,得先找到选中的那一个option才行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:53:06