将完整的网页放入document.write();

时间:2018-11-09 12:18:41

标签: javascript html

我无法使用弹出窗口的代码链接到另一个页面,因此我必须使用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>

1 个答案:

答案 0 :(得分:0)

有2个问题:

1您使用了错误的双引号

myWindow.document.write("<div>
<div id="test">

应该是

myWindow.document.write("<div>
<div id='test'>

2在JavaScript中,不能使用使用双引号的换行符

这是错误的

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?