JavaScript不修改原有代码实现下拉选中后展示对应数组文本
你可以直接在原有的window.onload函数里追加监听逻辑即可,不需要修改你已经写好的数组定义、FillMenuWithArray函数等现有代码,实现效果如下:
- 页面加载完成后默认显示第一个下拉选项对应的文本
- 切换下拉选项时自动更新为对应下标的text数组内容
完整可运行代码
<!DOCTYPE html> <html> <script> var property = new Array(); property[0] = "Acceleration"; property[1] = "Area"; property[2] = "Lenght"; property[3] = "Weigth"; var text = new Array(); text[0] = "Aceleration is the first value of converter"; text[1] = "Area is the second value of converter"; text[2] = "Aceleration is the first value of converter"; text[3] = "Area is the second value of converter"; function FillMenuWithArray(myMenu, myArray) { var i; myMenu.length = myArray.length; for (i = 0; i < myArray.length; i++) { myMenu.options[i].text = myArray[i]; } } window.onload = function(e) { FillMenuWithArray(document.property_form.the_menu, property) // 新增功能代码开始 const selectEl = document.querySelector('.select-property') const textEl = document.getElementById('text') // 初始化展示默认选中项的文本 textEl.innerText = text[selectEl.selectedIndex] // 监听下拉选择变更事件 selectEl.addEventListener('change', function() { textEl.innerText = text[this.selectedIndex] }) // 新增功能代码结束 } </script> <body> <h2>What Can JavaScript Do?</h2> <form name="property_form"> <span> <select class="select-property" name="the_menu"> </select> </span> </form> <br> <br> <p id="text">Text</p> </body> </html>
如果你需要把页面内容转为中文,直接修改property、text数组里的内容和h2标签的文本即可,功能逻辑不受影响。
内容的提问来源于stack exchange,提问作者Guilherme
相关产品推荐
相关产品推荐

