首先说一下这个小功能的应用场景
第一个页面
跳转的页面
就是实现ID的一个传值,但是第一个页面的表格是通过JSTL实现的不能够静态的给每一行表格信息起一个ID名称
<c:forEach items="${persons}" var = "person" varStatus="s">
<tr>
<td id="UserId">${s.count}</td>
<td>${person.name}</td>
<td>${person.gender}</td>
<td>${person.age}</td>
<td>${person.address}</td>
<td>${person.qq}</td>
<td>${person.email}</td>
<td><a class="btn btn-default btn-sm" onclick="updateUserLocation(this)" id="updateUserA">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td>
</tr>
</c:forEach>
一开始我打算使用父页面传递子页面的方式来实现这个功能
//父页面传递子页面数据传递方法
// function updateUserLocation(node) {
// var tr = node.parentNode.parentNode
// alert(tr.cells[0].innerText)
// // window.location="/web4/update.jsp"
// window.open("/web4/update.jsp")
// }
通过windos.open打开新的页面,然后在新的页面查找到数据,window.opener就可以打开父类的window对象.然后通过document获取各种元素信息.但是这种方式却让我失败了,原因就是getElementByID()中的名字获取父类的时候没有办法确定是哪一行的ID,位置无法确定,只会读取到第一行的TableRow对象,一开始以为我不能使用ID标签获取,应该使用Class属性,但是最后依然要回归到如何获取位置,所有这种方法就被我舍弃 了.
// var updateUserId = window.opener.document.getElementById("updateUserA").parentNode.parentNode
//
// var UserId = document.getElementById("id")
// alert(updateUserId)
// UserId.value=updateUserId.cells[0].innerText
使用Cookie实现数据的传递
这种方式就很稳妥了,
第一个页面的</+script>标签中的JS函数代码
function SetCookie(cookieName,cookieValue) {
/*设置Cookie值*/
document.cookie = cookieName + "=" + escape(cookieValue)
}
function updateUserLocation(node) {
var tr = node.parentNode.parentNode
var username = tr.cells[0].innerText ;
if(username.length>0 && username) {
SetCookie("userIdA", username);
/*跳转到b.html页面*/
document.location = "/web4/update.jsp";
}
}
下面是接受数据页面的</+script>标签中的JS函数代码
function ReadCookie(cookie_name){
//判断是否存在cookie
if (document.cookie.length > 0){
//查询cookie开始部分
cookie_start = document.cookie.indexOf(cookie_name + "=")
//如果存在
if (cookie_start != -1){
//计算结束部分
cookie_start = cookie_start + cookie_name.length + 1
cookie_end = document.cookie.indexOf(";", cookie_start)
//如果已经是最后一个cookie值,则取cookie长度
if (cookie_end == -1) {
cookie_end = document.cookie.length
}
//获取cookie值,unescape对特殊字符解密
return unescape(document.cookie.substring(cookie_start,cookie_end))
}
}
//其它情况返回空
return ""
}
window.onload = function init() {
var userinputId = ReadCookie("userIdA");
if(userinputId && userinputId.length>0) {
var UserId = document.getElementById("id")
UserId.value=userinputId;
}
}
最终我也是实现了我预期的目的,这个时候我其实还想扩展一下,使用Cookie来传递一个对象,这样就不仅仅可以ID自动填入,其他的input属性也可以自动的填入,
版权声明:本文为drankness原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。