如何将输入元素内容传入h3标签且不更新页面URL
问题解决:点击按钮仅更新h3标签内容,不修改浏览器URL
问题现状
点击页面中的Submit按钮后,浏览器地址栏URL被更新,同时页面中的h3标签内容未按预期显示包含输入参数的URL。需求是仅更新h3内容,不改变URL。
问题原因
- 表单默认提交行为:form标签内的button默认是
submit类型,点击会触发表单提交,导致页面刷新并将输入参数拼到URL上,这就是地址栏变化的原因。 - JS变量获取时机与方式错误:页面加载时就获取输入框的
innerHTML(输入框的内容实际存储在value属性而非innerHTML),且此时输入框为空,导致后续生成的newURL始终是初始URL加空参数,点击按钮时无法更新为输入后的内容。
解决方案
步骤1:阻止表单默认提交
给button添加type="button",避免触发表单提交行为:
<button id="button" type="button" onclick="updateURL()">Submit</button>
步骤2:修正JS逻辑,实时获取输入值
将输入框值的获取移到点击事件函数内部,确保每次点击都能拿到最新输入内容,同时改用value属性获取输入值:
let urlElement = document.getElementById("url"); const baseURL = urlElement.innerHTML; function updateURL() { const name = document.getElementById("name").value; const year = document.getElementById("year").value; const newURL = `${baseURL}?name=${name}&year=${year}`; urlElement.innerHTML = newURL; }
修改后的完整代码
HTML文件
<!DOCTYPE html> <html> <head> </head> <body> <form> <h3 id="url">https://localhost:8080/</h3> <label for="name">Name :</label><br> <input type="text" id="name" name="name"><br> <label for="year">Graduation Year :</label><br> <input type="number" id="year" name="year"><br> <button id="button" type="button" onclick="updateURL()">Submit</button> </form> <script src="app.js"></script> </body> </html>
JavaScript文件
let urlElement = document.getElementById("url"); const baseURL = urlElement.innerHTML; function updateURL() { const name = document.getElementById("name").value; const year = document.getElementById("year").value; const newURL = `${baseURL}?name=${name}&year=${year}`; urlElement.innerHTML = newURL; }
内容的提问来源于stack exchange,提问作者Md Amir Sohail
相关产品推荐
相关产品推荐

