首页 > 解决方案 > 如何编写对 window.open 函数的元素引用?

问题描述

所以,我开始在 javascript 中使用“window.open”,很快就被卡住了。

在我的示例代码中,有一个 id 为“reference”的 ap 标记,以及一个调用函数的按钮,该函数旨在将该 p 标记写入新选项卡。

我将如何正确引用 p 标签并将其写入新标签?

到目前为止,我只使用下面的代码获得了“[object HTMLParagraphElement]”......

HTML

<p id="reference">This is some placeholder text meant for another page.</p>

<button onclick="createTab()">Create Tab</button>

JavaScript

function createTab() {
  var myWindow = window.open("", "Test");
  myWindow.document.write(document.getElementById("reference"));
}

标签: javascripthtmltabswindow

解决方案


我认为您可以使用以下内容代替 document.write:

myWindow.document.appendChild(document.getElementById("reference"))

希望能解决您的问题。


推荐阅读