如何编写脚本从完整表单中单独提取单个值,实现提交值差异化样式展示
实现步骤及可运行代码示例
1. 编写表单提交页(index.html)
GET方式提交表单时,输入框的name属性会作为参数名拼接到跳转URL中,是后续参数识别的核心,必须给每个输入框设置唯一的name值:
<!DOCTYPE html> <html> <body> <!-- action属性填写结果页的文件路径 --> <form action="result.html" method="GET"> <label>第一个输入项:</label> <input type="text" name="firstContent" required> <br><br> <label>第二个输入项:</label> <input type="text" name="secondContent" required> <br><br> <button type="submit">提交并跳转</button> </form> </body> </html>
2. 编写结果展示页(result.html)
直接用浏览器原生的URLSearchParams解析GET参数即可,不需要手动切割URL,行内样式的渲染逻辑直接写在脚本里即可:
<!DOCTYPE html> <html> <body> <h2>提交结果展示</h2> <div id="leftBox"></div> <div id="rightBox"></div> <script> // 解析URL里的GET参数 const params = new URLSearchParams(window.location.search) // 按name获取对应输入值,加默认值避免用户空提交报错 const firstVal = params.get('firstContent') || '未输入第一个内容' const secondVal = params.get('secondContent') || '未输入第二个内容' // 获取DOM节点,插入内容+设置行内样式 const leftBox = document.getElementById('leftBox') leftBox.innerText = firstVal leftBox.style = ` width: 45%; float: left; padding: 15px; margin: 20px 2%; border: 1px solid #ddd; background: #f5f5f5; ` const rightBox = document.getElementById('rightBox') rightBox.innerText = secondVal rightBox.style = ` width: 45%; float: right; padding: 15px; margin: 20px 2%; border: 1px solid #ddd; background: #e8f4ff; text-align: right; ` </script> </body> </html>
核心注意事项
- 如果后续要新增更多输入项,只要在表单页加对应
name的输入框,结果页新增对应DOM节点、写自定义样式逻辑即可 - 如果你不需要动态修改样式,也可以把固定样式提前写在
<style>标签的CSS类中,给DOM节点加class属性即可,比行内样式更易维护 URLSearchParams兼容所有现代浏览器,不需要额外引入第三方工具
内容的提问来源于stack exchange,提问作者Snugman
相关产品推荐
相关产品推荐

