---
title: "window.opener  checkbox传值问题"
author: "加菲学Java"
date: "2011-11-25T20:30:30Z"
tags: []
categories: ["Web前端"]
slug: "window-opener-checkbox"
draft: false
lastmod: "2011-11-25T20:31:34Z"
id: 1278616
url: "https://yklovejava-163-com.iteye.com/blog/1278616"
---

今天遇到页面之间的传值问题，一个页面以window.open()的方式打开一个新的页面，要把device.jsp页面列表中所有的

checkbox:像下面这样

 

```
<form name="queryListForm">
    <input type="checkbox" name="deviceList" value="device1"/> 
    <input type="checkbox" name="deviceList" value="device2"/> 
    <input type="checkbox" name="deviceList" value="device3"/> 
    ......
</form>
```

 

 传到deviceIssued.jsp页面中。

 这里有两种方式：

 第一种就是url地址传值，但是这样是有问题的，url传值是有长度限制的，一旦数据多的时候，就无法全部传递，所有这种方式只能放弃。

 第二种就是：

 

```
window.opener
```

 

 的方式获取父窗体的节点。

 

 

```
var deviceList = window.opener.document.queryListForm.deviceList;
var length = deviceList.length;
var checkValue = [];
for (i = 0; i < length; i++) {
	if(deviceList[i].checked) { // 判断checkbox是否被选择
		checkValue.push(deviceList[i].value);
	}
}
```

 

 

      但是写完测试后发现有个问题，选多个checkbox是没有问题的，但是只选择一个的时候就无法传递，用firebug进行了debug调试，发现只选择一个checkbox的时候length是undefined，选择多个的时候就没有问题，可以取得长度数值  。怎么试也没用，以为是浏览器的缓存问题，还关机重启了一下，结果发现还是不行。

      没办法，只能再用firebug再继续debug调试，这时候发现选择多个checkbox的时候deviceList其实是一个数组,deviceList.length肯定是能取到值的。而只选择一个的时候就是一个节点对象，

这时是没有deviceList.length是取不到任何值的，只会返回undefiend。所以这时必须得判断是选择多个还是一个，

即判断var length 是否是undefiend.

最后的代码改为如下即可：

 

 

```
$(function() {
	var deviceList = window.opener.document.queryListForm.deviceList;
	var length = deviceList.length;
	
	if(length == undefined) { // 只选择了一个checkbox
		$("#deviceParamList").val(deviceList.value);
	}else { // 选择了多个checkbox
		var checkValue = [];
		for (i = 0; i < length; i++) {
			if(deviceList[i].checked) { // 判断checkbox是否被选择
				checkValue.push(deviceList[i].value);
			}
		}
	
		$("#deviceParamList").val(checkValue);
	}
});
```