如何将选中option的三个值分别输出至独立div?
解决方案
步骤1:修改HTML结构
把原来的单个输出容器换成三个独立的<div>,每个分配唯一ID,方便后续单独控制样式和赋值:
<select id="Namiddag" name="Namiddag" data-name="Namiddag" class="js-basic-single" onChange="selectedAfternoon(this);"> <option></option> <option id="13x19namiddag" value="Namiddag|13x19 cm|€12,50">13x19 cm, €12.50</option> <option id="20x30namiddag" value="Namiddag|20x30 cm|€22,50">20x30 cm, €22.50</option> <option id="30x45namiddag" value="Namiddag|30x45 cm|€32,50">30x45 cm, €32.50</option> <option class="disabled" value="disabled" disabled="disabled">Wil je meer stuks of formaten van deze foto? Vermeld dit dan in de winkelwagen., </option> </select> <!-- 三个独立输出容器,可单独设置样式 --> <div id="output-category-afternoon"></div> <div id="output-size-afternoon"></div> <div id="output-price-afternoon"></div>
步骤2:更新JS逻辑
通过split('|')把选项值拆分成数组,再分别赋值给对应的div,同时处理空选择或禁用选项的情况:
function selectedAfternoon(element) { const selectedValue = element.options[element.selectedIndex].value; // 清空所有输出(处理未选/禁用选项) document.getElementById("output-category-afternoon").textContent = ''; document.getElementById("output-size-afternoon").textContent = ''; document.getElementById("output-price-afternoon").textContent = ''; // 仅处理有效选项值 if (selectedValue && selectedValue !== 'disabled') { const [category, size, price] = selectedValue.split('|'); document.getElementById("output-category-afternoon").textContent = category; document.getElementById("output-size-afternoon").textContent = size; document.getElementById("output-price-afternoon").textContent = price; } }
关键说明
- 用
split('|')将选项值按分隔符拆分成三个独立部分,解构赋值让代码更清晰 - 每个输出div可以单独编写CSS样式(比如设置不同的对齐方式、字体样式、间距等)
- 加入判断逻辑,避免选中无效选项时输出错误内容
内容的提问来源于stack exchange,提问作者user16358489
相关产品推荐
相关产品推荐

