如何实现下拉列表select选中后同时显示厘米数与对应价格
问题修正:下拉选择后分别显示高度与价格
原代码存在的问题
- Option的value同时拼接价格和高度,无法直接区分两个独立值
- HTML中div元素重复定义
class属性,违反HTML语法规范 - JS选择器错误:
next('.divprice')无法选中目标元素,因为next()仅能获取紧邻的兄弟节点 - JS存在语法错误:条件语句缺少闭合括号,语句未加分号
- 逻辑错误:将混合的value值同时用于高度和价格展示,导致输出混乱
修正方案与完整代码
1. 调整Option的属性存储逻辑
将价格存入value,高度存入自定义data-height属性,避免值混淆;
2. 修复HTML的class属性定义;
3. 重写JS函数,正确获取并展示对应值。
完整代码如下:
<label>Select Height</label> <select name="psheight" id="psheight" style="width:50%;" class="form-control form-control-sm rounded-0" onchange="changeddl(this)"> <?php $conn = $pdo->open(); try{ $stmt = $conn->prepare("SELECT * FROM customize_ps_height"); $stmt->execute(); foreach($stmt as $row){ ?> <option value="<?php echo $row['price'];?>" data-height="<?php echo $row['height'];?>"><?php echo $row['height']; ?></option> <?php } } catch(PDOException $e){ echo $e->getMessage(); } $pdo->close(); ?> </select> <div class="divheight height-style"></div> <div class="divprice price-style"></div> <script> function changeddl(selectEl) { // 获取选中选项的价格和高度 const selectedOption = selectEl.options[selectEl.selectedIndex]; const price = selectedOption.value; const height = selectedOption.dataset.height; // 定位并更新对应div内容 const divHeight = selectEl.nextElementSibling; const divPrice = divHeight.nextElementSibling; if (price > 0 && height) { divHeight.textContent = `Height: ${height} cm`; divPrice.textContent = `Price: ₱${price}`; } else { divHeight.textContent = ''; divPrice.textContent = ''; } } </script>
代码说明
- 使用
data-height属性存储高度,让value仅保留价格,符合语义化规范 - 通过
selectEl.options[selectEl.selectedIndex]精准获取选中的选项元素 - 用
nextElementSibling依次获取紧邻的div元素,避免选择器错误 - 完善空值判断,确保未选中有效选项时清空显示内容
内容的提问来源于stack exchange,提问作者Sencho
相关产品推荐
相关产品推荐

