gpt4 book ai didi

javascript - 尝试打开一个新窗口并在其中创建元素

转载 作者:行者123 更新时间:2023-11-28 03:27:51 25 4
gpt4 key购买 nike

所以我一直在尝试做的是打开一个新的小窗口,其大小为 500x500,并在其中创建包含 JS/Jquery 的新 div。

html:

<body>
<div class="contain "> </div>
</body>
newWindow = window.open("replaceWindow.html", "newWindow", "width=500,height=500");

newWindow.onload = () =>{
let newDiv = newWindow.document.createElement("div");
newDiv.className = "card-body"
newWindow.document.getElementByClassName('contain').appendChild(newDiv);
}

仍然contain不附加newDiv

最佳答案

首先,当加载您的第一个初始窗口时,它就会被缓存。因此,当从第一个窗口创建窗口时,新窗口的内容不是从服务器加载,而是从缓存加载。因此,当您创建窗口时,不会发生onload事件。

但是,在这种情况下,会发生 onpageshow 事件。它始终发生在 onload 事件之后,甚至当页面从缓存加载时也是如此。

w3school website 对此进行了解释:

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

因此,这是使用 newWindow 上的 onpageshow 事件监听器而不是 onload 来解决您的问题的有效解决方案:

var newWindow = window.open("replaceWindow.html", "newWindow", "width=500,height=500");

newWindow.onpageshow = () => {
let newDiv = newWindow.document.createElement("div");
newDiv.className = "card-body";
newWindow.document.getElementsByClassName('contain').item(0).appendChild(newDiv);
}

关于javascript - 尝试打开一个新窗口并在其中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58465446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com