实现加减按钮控制输入框显示自定义文本而非数字的技术需求
解决方案:点击加减按钮切换输入框文本状态
嘿,这个需求其实很好实现,核心思路就是把数字状态和对应的德语文本做一个映射,然后通过按钮点击来切换当前的状态索引,再更新输入框的显示内容就行。我给你写了一个完整可运行的示例:
HTML 结构
<div class="rating-container"> <button id="decreaseBtn">-</button> <input type="text" id="ratingInput" readonly value="Ok"> <button id="increaseBtn">+</button> </div>
这里把输入框设为readonly,避免用户手动修改内容,只通过按钮来控制显示。
JavaScript 逻辑
// 定义状态映射:索引对应数字-2、-1、0、1、2,值是对应的文本 const ratingTexts = ["sehr schlecht", "schlecht", "Ok", "gut", "sehr gut"]; // 默认选中的是索引2(对应Ok) let currentIndex = 2; // 获取DOM元素 const decreaseBtn = document.getElementById('decreaseBtn'); const increaseBtn = document.getElementById('increaseBtn'); const ratingInput = document.getElementById('ratingInput'); // 减号按钮点击事件 decreaseBtn.addEventListener('click', () => { if (currentIndex > 0) { currentIndex--; ratingInput.value = ratingTexts[currentIndex]; } }); // 加号按钮点击事件 increaseBtn.addEventListener('click', () => { if (currentIndex < ratingTexts.length - 1) { currentIndex++; ratingInput.value = ratingTexts[currentIndex]; } });
关键说明
ratingTexts数组按照从最差到最好的顺序排列,对应你需要的--到++的文本逻辑,索引直接对应状态的切换路径- 点击按钮时会先判断当前索引是否在数组边界内,避免出现越界导致的错误
- 如果需要显示带符号的完整文本(比如
-- (sehr schlecht)),直接修改ratingTexts数组内容即可,比如改成:["-- (sehr schlecht)", "- (schlecht)", "0 (Ok)", "+ (gut)", "++ (sehr gut)"]
内容的提问来源于stack exchange,提问作者Mile Mijatović
相关产品推荐
相关产品推荐

