将变量从子弹出窗口 window 传递到父弹出窗口 window
Passing Variable from child popup window to parent popup window
我有 PopUp window 转到 upload.jsp,它将文件上传到目录。
上传逻辑写在upload.jsp中。我的问题是我想获取父弹出窗口的保存路径 window 文本字段。
childwindow有一个属性,opener
,指的是打开它的window。如果它们来自同一来源,child 可以像这样访问 parent 上的全局变量:
opener.globalVariable
这意味着它可以作为 opener.document
访问 parent window 的文档,因此可以使用 opener.document.getElementById
或 opener.document.querySelector
来获取元素在 parent window.
示例:
Parent 页数:
<!doctype html>
<html lang="en">
<body>
<input type="text"><input type="button" value="Click me">
<script>
document.querySelector("input[type=text]").value = Math.floor(Math.random() * 10000);
document.querySelector("input[type=button]").addEventListener(
"click",
function() {
var wnd = window.open("popup.html");
},
false
);
</script>
</body>
</html>
弹出页面:
<!doctype html>
<html>
<body>
<script>
var field;
if (!opener) {
display("Not opened as a popup");
} else {
field = opener.document.querySelector("input[type=text]");
display("Value is " + field.value);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
</script>
</body>
</html>
我有 PopUp window 转到 upload.jsp,它将文件上传到目录。
上传逻辑写在upload.jsp中。我的问题是我想获取父弹出窗口的保存路径 window 文本字段。
childwindow有一个属性,opener
,指的是打开它的window。如果它们来自同一来源,child 可以像这样访问 parent 上的全局变量:
opener.globalVariable
这意味着它可以作为 opener.document
访问 parent window 的文档,因此可以使用 opener.document.getElementById
或 opener.document.querySelector
来获取元素在 parent window.
示例:
Parent 页数:
<!doctype html>
<html lang="en">
<body>
<input type="text"><input type="button" value="Click me">
<script>
document.querySelector("input[type=text]").value = Math.floor(Math.random() * 10000);
document.querySelector("input[type=button]").addEventListener(
"click",
function() {
var wnd = window.open("popup.html");
},
false
);
</script>
</body>
</html>
弹出页面:
<!doctype html>
<html>
<body>
<script>
var field;
if (!opener) {
display("Not opened as a popup");
} else {
field = opener.document.querySelector("input[type=text]");
display("Value is " + field.value);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
</script>
</body>
</html>