如何在页面多处显示JavaScript变量?含下拉列表显示问题
Hey there! Let's sort out why only the first <span class="kid-name"> gets updated with the student name when you click the "Next" button.
问题根源
Your current JavaScript code uses document.getElementsByClassName("kid-name")[0].innerText = nameInput; — that [0] is the culprit! It only targets the first element with the kid-name class, leaving all the other spans in your dropdown options untouched.
解决方案:遍历所有匹配元素
You need to loop through every element with the kid-name class and update each one individually. Here are two straightforward ways to do this:
方法1:使用getElementsByClassName + 普通循环
function nextForm() { var nameInput = document.getElementById("kidNameInput").value; // 获取所有带kid-name类的元素 var kidNameElements = document.getElementsByClassName("kid-name"); // 逐个更新每个元素的文本 for (var i = 0; i < kidNameElements.length; i++) { kidNameElements[i].innerText = nameInput; } }
方法2:使用querySelectorAll + forEach(更现代简洁)
function nextForm() { var nameInput = document.getElementById("kidNameInput").value; // 选中所有.kid-name元素 var kidNameElements = document.querySelectorAll(".kid-name"); // 遍历并更新每个元素 kidNameElements.forEach(element => { element.innerText = nameInput; }); }
额外小提示
Some browsers have quirky support for <span> tags inside <option> elements. If you run into display or styling issues later, you could adjust your approach to avoid nested spans:
- Store the base text of each option in a
dataattribute, like this:<option value="0" data-text="did a great job at…"></option> <option value="1" data-text="did this…"></option> - Then update the option text directly in your JS:
kidNameElements.forEach(element => { element.textContent = `${nameInput} ${element.dataset.text}`; });
Either way, the core fix is to stop targeting just the first element — loop through all matches, and every instance of kid-name will show the student's name!
内容的提问来源于stack exchange,提问作者kashby

