我有一个现有的HTML文件,如下所示-
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/ html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="chatWindow.css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chat Window</title>
</head>
<body>
<table>
<tr> <textarea id="chatTextArea" rows="20" cols = "80"></textarea> </tr>
<tr> <textarea id="messageTextArea" rows="5" cols="80"></textarea> </tr>
</table>
<script type="text/javascript" src ="jquery-1.7.1.js" ></script>
<script type="text/javascript" src="liveChat.js"></script>
</body>
</html>
我在一个新窗口中从JavaScript代码中打开这个HTML,如下所示-
var chatWindow = window.open("chatWindow.html", "Chat Window", "resizable=0,width=700,height=600");
现在,我想在此现有窗口中添加另一个字段。我试过了-
var chatWindow = window.open("chatWindow.html", "Chat Window", "resizable=0,width=700,height=600");
chatWindow.document.write(' Hey!! <input type="hidden" id="currentUserName" value="' + userName+ '" / > ');
但这覆盖了现有的HTML,所以我在页面上看到的只是"嘿!!"。
我也试过
var chatWindow = window.open("chatWindow.html", "Chat Window", "resizable=0,width=700,height=600");
var hiddenNode = chatWindow.document.createElement('input');
hiddenNode.setAttribute("type", "hidden");
hiddenNode.setAttribute("id", "currentUserName");
hiddenNode.setAttribute("value", userName);
chatWindow.document.body.appendChild(hiddenNode);
但这并没有影响。当新窗口打开时,我检查了它的页面源,但没有找到隐藏的节点。如何解决这个问题?请帮忙。
您应该使用appendChild。
chatWindow.document.appendChild(document.createTextNode("Hey !"));
您也可以使用jQuery来更容易地做到这一点。
尝试分配属性而不是属性。
chatWindow = window.open("chatWindow.html"...);
hiddenNode=chatWindow.document.body.appendChild(chatWindow.document.createElement('INPUT'));
hiddenNode.type='hidden';
hiddenNode.id='currentUserName';
hiddenNode.value=userName;
编辑:
如果浏览器在新选项卡中打开窗口,则也可以通过chatWindow
访问该窗口。(用Chrome、FF和IE成功测试。)
尝试chatWindow.document.body.appendChild(/* [...] */);
。