如何用JavaScript与查询字符串在单文件内实现用户名问候功能
单文件实现用户名问候功能(基于Query String和onload事件)
需求背景
原本通过两个HTML文件实现表单输入用户名并显示问候的效果,现需改为单个文件完成,要求使用query string传递参数,结合onload事件处理展示逻辑。
原双文件代码示例:
firstpage.html
<input type="text" id="titletxt"> <button onclick="Submit()">Submit</button> <script> function Submit() { let name = document.getElementById("txtname").value; window.location.href = "secondpage.html?" + name; } </script>
secondpage.html
<html> <head> <title>Test</title> <script> function loadTitle() { let queryString = window.location.search.split('?')[1]; document.write("<h2>Hello "+queryString+"</h2>") document.title = "hello "+queryString; } </script> </head> <body onload="loadTitle()"> </body> </html>
解决方案
以下是整合后的单文件代码,同时修复了原代码中输入框ID与JS获取ID不匹配的问题:
<!DOCTYPE html> <html> <head> <title>Test</title> <script> function Submit() { // 获取输入框的值,统一ID为txtname let name = document.getElementById("txtname").value.trim(); if (name) { // 跳转到当前页面,拼接规范的查询参数(用encodeURIComponent处理特殊字符) window.location.href = window.location.pathname + "?name=" + encodeURIComponent(name); } } function loadGreeting() { // 解析查询参数 const params = new URLSearchParams(window.location.search); const userName = params.get('name'); if (userName) { // 解码特殊字符,显示问候语 const decodedName = decodeURIComponent(userName); document.getElementById('greeting-area').innerHTML = `<h2>Hello ${decodedName}</h2>`; document.title = `Hello ${decodedName}`; // 可选:隐藏表单,只显示问候 // document.getElementById('form-area').style.display = 'none'; } } </script> </head> <body onload="loadGreeting()"> <!-- 表单区域 --> <div id="form-area"> <input type="text" id="txtname" placeholder="请输入用户名"> <button onclick="Submit()">Submit</button> </div> <!-- 问候语显示区域 --> <div id="greeting-area"></div> </body> </html>
关键说明
- 参数传递:表单提交时,将用户名通过
?name=xxx的查询参数拼接到当前页面URL,使用encodeURIComponent处理特殊字符(如空格、中文)避免乱码。 - onload事件处理:页面加载时,通过
URLSearchParams解析查询参数,若存在用户名则显示问候语并修改页面标题。 - 兼容性与体验:保留表单区域,用户可再次输入新用户名;也可通过注释代码隐藏表单,仅展示问候内容。
内容的提问来源于stack exchange,提问作者user20481542
相关产品推荐
相关产品推荐

