在新窗口中使用javascript更改innerHTML



我正试图用下面的代码通过javascript在另一个窗口中编辑列表项的innerHTML。

function searchNameButton() //this function is called when the user clicks the search by name button.
{
name = document.getElementById("nmSearch").value;
window = window.open("search.html"); //opens a new window, can be accessed through this window variable
matchIndexes = [];
for (i = 0; i < pokemon.length; i++) //do the actual search here
{
if (pokemon[i][1].toLowerCase().includes(name.toLowerCase())) //converts to lowercase so that the search is case-insensitive
{ 
matchIndexes.push(i);
}
}
//now to populate the new page, similar to how it was done before
itemList = window.document.getElementsByClassName("pd");
console.log(matchIndexes);
for (i = 0; i < itemList.length; i++)
{
itemList[i].innerHTML = generateString(pokemon[matchIndexes[i]]);
}
}

但是,当新窗口打开时,不会有任何更改。我确信matchIndexes是有效的,我输出了它的值,它在我的测试用例中找到了3个匹配项(应该是这样(,类似地,当我将其输出到控制台时,itemList正确地填充了20个项。然而,更改这些项中任何一项的innterHTML,即使在for循环之外作为测试进行更改,也无济于事。我不确定我的错误到底是什么。

为了澄清起见,generateString((函数在其他地方运行良好,即使在最坏的情况下也不可能输出空字符串。至少它会输出一些字符,然后我可以在检查器中看到这些字符。

如有任何帮助,我们将不胜感激。

window.open()强调

请注意,远程URL不会立即加载。当window.open()返回时,窗口始终包含about:blank。URL的实际获取被推迟,并在当前脚本块完成执行后开始。窗口的创建和引用资源的加载是异步完成的。

由于Window似乎有一个onload处理程序,我会简单地尝试将窗口更改部分包装成一个事件处理程序:

function searchNameButton() //this function is called when the user clicks the search by name button.
{
name = document.getElementById("nmSearch").value;
wnd = window.open("search.html"); //opens a new window, can be accessed through this wnd variable
matchIndexes = [];
for (i = 0; i < pokemon.length; i++) //do the actual search here
{
if (pokemon[i][1].toLowerCase().includes(name.toLowerCase())) //converts to lowercase so that the search is case-insensitive
{ 
matchIndexes.push(i);
}
}
wnd.onload = function()
{
//now to populate the new page, similar to how it was done before
itemList = wnd.document.getElementsByClassName("pd");
console.log(matchIndexes);
for (i = 0; i < itemList.length; i++)
{
itemList[i].innerHTML = generateString(pokemon[matchIndexes[i]]);
}
};
}

但是,我还没有真正尝试过,所以它可能起作用,也可能不起作用。如果没有,我会在处理程序的最开始添加一些伪日志,看看它是否被调用,然后添加一行console.log(itemList);,看看getElementsByClassName()调用是否找到了什么。