我无法使用弹出窗口的代码链接到另一个页面,因此我必须使用document.write,但是当我单击按钮时,它甚至都无法打开弹出窗口。 例如,此代码有效:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<script>alert('test')<\/script>");
myWindow.document.close();
var p = document.createElement("p")
p.innerHTML = "This is the source window!";
opener.document.querySelector("body").appendChild(p)
}
</script>
但是,当我添加分隔符之类的元素时,它不起作用。例如:
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<div>
<div id="test">
<p>Test</p>
<br>
</div>
</div>");
myWindow.document.close();
var p = document.createElement("p")
p.innerHTML = "This is the source window!";
opener.document.querySelector("body").appendChild(p)
}
</script>
答案 0 :(得分:0)
有2个问题:
myWindow.document.write("<div>
<div id="test">
应该是
myWindow.document.write("<div>
<div id='test'>
这是错误的
myWindow.document.write("<div>
<div id="test">
<p>Test</p>
应该是
myWindow.document.write("<div><div id="test"><p>Test</p>....
最后
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<div><div id='test'><p>Test</p><br></div></div>");
myWindow.document.close();
var p = document.createElement("p")
p.innerHTML = "This is the source window!";
opener.document.querySelector("body").appendChild(p)
}
</script>
如果要用JS编写html,请参考What is the usage of the backtick symbol (`) in JavaScript?