如何将HTML文本框输入的段落数据展示到另一个页面?
问题排查
你的代码跑不通是几个低级错误叠在一起导致的:
- HTML结构不规范:
link、script标签被放到了<head>标签外面,浏览器解析时可能出现资源加载异常 - 传值逻辑前后不一致:提交时你把内容存到了
localStorage,但归档页加载时却去URL参数里读内容,两边根本对不上 - 表单默认提交行为冲突:你给submit按钮绑了onclick事件,但表单默认的post提交会直接跳转,大概率localStorage还没写完页面就跳走了;而且
<textarea>没加name属性,就算改成get提交也带不上参数 - 缺少公告页自身的内容展示逻辑:你要求公告页也要展示采集到的内容,现有代码完全没写这部分
- 存在XSS风险:直接用
innerHTML插入用户输入内容,用户输入恶意脚本会被直接执行
修正后代码
1. 公告页(采集+自身展示页)
修正HTML结构,新增本页内容展示区,调整表单绑定逻辑:
<!DOCTYPE html> <html> <head> <title>Announcement Page</title> <link rel="stylesheet" href="stylem.css" /> <script type="text/javascript" src="index.js"></script> </head> <body> <!-- 本页公告展示区 --> <div id="announcement-show" style="margin: 20px 0; padding: 10px; border: 1px solid #eee; display: none;"> <h3>当前公告内容:</h3> <p id="local-content"></p> </div> <form id="announce-form" action="archive.html"> <textarea type="text" id="textbox" class="textbox" cols="40" rows="10" placeholder="请输入公告内容"></textarea> <br> <input type="submit" id="save" name="save" value="submit" /> </form> </body> </html>
2. 公告页配套JS(index.js)
移除内联事件绑定,统一处理提交逻辑、本地存储、本页渲染、页面跳转:
window.addEventListener('load', () => { // 页面加载时先读取本地存储的历史公告,直接在本页展示 const savedContent = localStorage.getItem("announcementData"); const showArea = document.getElementById('announcement-show'); const localContent = document.getElementById('local-content'); if (savedContent) { showArea.style.display = 'block'; // 替换换行符保留段落格式 localContent.innerHTML = savedContent.replace(/\n/g, '<br>'); } // 绑定表单提交事件 const form = document.getElementById('announce-form'); form.addEventListener('submit', (e) => { // 阻止表单默认跳转行为,等逻辑执行完再手动跳 e.preventDefault(); const textValue = document.getElementById('textbox').value.trim(); if (!textValue) { alert('请输入公告内容'); return; } // 内容存入本地存储 localStorage.setItem("announcementData", textValue); // 更新本页展示 showArea.style.display = 'block'; localContent.innerHTML = textValue.replace(/\n/g, '<br>'); // 跳转至归档页 window.location.href = 'archive.html'; }) })
3. 归档页(archive.html)
补上读取本地存储的逻辑,修正内容渲染规则:
<!DOCTYPE html> <html> <head> <title>Archive</title> <link rel="stylesheet" href="stylea.css" /> <script> window.addEventListener('load', () => { // 直接读取本地存储的公告内容 const savedContent = localStorage.getItem("announcementData"); const resultDom = document.getElementById('result-text'); if (savedContent) { // 替换换行符保留段落格式 resultDom.innerHTML = savedContent.replace(/\n/g, '<br>'); } else { resultDom.textContent = '暂无公告内容'; } }) </script> </head> <body> <h2> Announcement : <span id="result-text"> </span></h2> </body> </html>
补充说明
- 上述实现支持保留输入的段落换行,提交后公告页、归档页都能正常展示内容,刷新页面也不会丢失
- 注意
localStorage是存在用户本地浏览器的,换浏览器、清空浏览器缓存后内容会消失,如果需要所有访问者都能看到同一份公告,需要额外搭配后端接口存储数据,纯前端静态页无法实现跨用户的数据同步
内容的提问来源于stack exchange,提问作者BattleLion
相关产品推荐
相关产品推荐

