document.getElementById().innerHTML不生效但可打印元素值的问题排查
问题原因与解决方案
问题根源
你的按钮嵌套在<form>标签中,浏览器默认会把未指定type的<button>解析为提交按钮(submit类型)。点击后会触发表单提交,导致页面刷新——虽然main()函数确实修改了占位符的内容,但页面刷新后会重置回初始状态,所以你看不到更新后的文本。控制台能打印值是因为代码执行在页面刷新之前。
两种修复方法
方法1:修改按钮类型为button
给按钮添加type="button"属性,让它不再触发表单提交:
<button type="button" onclick="main()">Get score!</button>
方法2:在main函数中阻止表单默认行为
修改main函数,添加阻止默认提交的逻辑,同时在调用时传入事件对象:
function main(event) { // 阻止表单默认提交行为 event.preventDefault(); let name = getNameOfOrganisation(); document.getElementById("namePlaceholder").innerHTML = "Name of organisation: " + name; console.log(name); let state = getStateOfOrganisation(); document.getElementById("statePlaceholder").innerHTML = "Points scored for state/territory: " + state; console.log(state); }
对应的HTML按钮需要传递事件参数:
<button onclick="main(event)">Get score!</button>
完整可运行代码示例(以方法1为例)
HTML代码
<h1>Organisation Score Calculator</h1> <form action=""> <h4>Input the name of the charity.</h4> <input type="text" id="nameOfOrganisation"> <h4>Which state/territory does this organisation service?</h4> <select name="state" id="state"> <option value="VIC">VIC</option> <option value="NSW">NSW</option> <option value="ACT">ACT</option> <option value="QLD">QLD</option> <option value="NT">NT</option> <option value="TAS">TAS</option> <option value="WA">WA</option> </select> <br> <br> <button type="button" onclick="main()">Get score!</button> <p id="namePlaceholder"></p> <p id="statePlaceholder"></p> </form>
JavaScript代码
function getNameOfOrganisation () { let organisation = document.getElementById("nameOfOrganisation").value; return organisation; } function getStateOfOrganisation () { let state = document.getElementById("state").value; if (state === "VIC") { let points = 1; return points; } else if (state === "NSW") { let points = 0.5; return points; } else { let points = 0; return points; } } function main () { let name = getNameOfOrganisation(); document.getElementById("namePlaceholder").innerHTML = "Name of organisation: " + name; console.log(name); let state = getStateOfOrganisation(); document.getElementById("statePlaceholder").innerHTML = "Points scored for state/territory: " + state; console.log(state); }
内容的提问来源于stack exchange,提问作者ssssspiral
相关产品推荐
相关产品推荐

