如何将网页中存储的Cookie数据展示到表格中?
你可以通过添加一个更新表格内容的函数,在Cookie数据变化或页面加载时同步数据到表格里。以下是修改后的完整代码:
function setCookie(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); let expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(';'); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } // 新增:更新表格内容的函数 function updateTable() { const username = getCookie("username"); const password = getCookie("password"); // 获取表格中的对应单元格 const nameCell = document.querySelector("#cookiesTable tbody tr td:first-child"); const passwordCell = document.querySelector("#cookiesTable tbody tr td:last-child"); // 填充Cookie数据 nameCell.textContent = username || "未设置用户名"; passwordCell.textContent = password || "未设置密码"; } function checkCookie() { let user = getCookie("username"); let password = getCookie("password"); if (user != "" && password != "") { alert("Welcome again " + user); // 已有Cookie时更新表格 updateTable(); } else { user = prompt("Please enter your name:", ""); password = prompt("Please enter your password:", ""); if (user != "" && user != null && password != "" && password != null) { setCookie("username", user, 30); setCookie("password", password, 30); // 设置Cookie后更新表格 updateTable(); } else { // 用户取消输入时也更新表格(显示默认提示) updateTable(); } } }
<body onload="checkCookie()"> <table id="cookiesTable" style="border:1px solid;"> <thead> <tr> <th>NAME</th> <th>PASSWORD</th> </tr> </thead> <tbody> <tr> <td>未设置用户名</td> <td>未设置密码</td> </tr> </tbody> </table> </body>
关键改动说明:
- 新增
updateTable函数:负责从Cookie中读取用户名和密码,然后将内容填充到表格对应的单元格中,如果Cookie为空则显示默认提示文本。 - 修改
checkCookie函数:在用户已有Cookie、设置新Cookie、取消输入这三种场景下,都调用updateTable确保表格内容和Cookie同步。 - 调整HTML表格的初始内容:替换原来的固定文本为默认提示,让页面加载时即使没有Cookie也有友好显示。
内容的提问来源于stack exchange,提问作者ttt
相关产品推荐
相关产品推荐

