点击select下拉框选项时如何获取选中option的name属性值
解决方案
你调用e.target.getAttribute("name")失败的原因是:e.target指向的是绑定事件的<select>元素本身,你拿到的会是select的name值abc,而非选中的<option>的属性。
需要先通过select元素的selectedIndex属性定位到当前选中的option节点,再读取该节点的name属性即可,修改后的处理函数代码如下:
function handleSelectButton(e) { // 获取select原生DOM节点 const selectDom = e.target; // 定位当前选中的option节点 const selectedOption = selectDom.options[selectDom.selectedIndex]; // 读取option的name属性 const optionName = selectedOption.getAttribute('name'); // 原有的value获取逻辑不受影响 const optionValue = selectDom.value; console.log('选中option的name值:', optionName); console.log('选中option的value值:', optionValue); }
该方案在你给出的React代码场景中可以直接运行,选中Apple选项时会打印出apple的name值。
内容的提问来源于stack exchange,提问作者Rajendra Bar
相关产品推荐
相关产品推荐

