在新窗口中使用 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() 函数,为了澄清,在其他地方工作正常,即使在最坏的情况下也不可能输出空字符串。至少它会输出一些我可以在检查器中看到的字符。


任何帮助,将不胜感激。



Smart猫小萌
浏览 129回答 1
1回答

拉风的咖菲猫

window.open()强调请注意,远程 URL 不会立即加载。返回时window.open(),窗口始终包含about:blank.&nbsp;实际获取 URL 会延迟并在当前脚本块执行完毕后开始。窗口创建和引用资源的加载是异步完成的。由于Window似乎有一个onload处理程序,我会简单地尝试将窗口更改部分包装到一个事件处理程序中:function searchNameButton() //this function is called when the user clicks the search by name button.{&nbsp; &nbsp; name = document.getElementById("nmSearch").value;&nbsp; &nbsp; wnd = window.open("search.html"); //opens a new window, can be accessed through this wnd variable&nbsp; &nbsp; matchIndexes = [];&nbsp; &nbsp; for (i = 0; i < pokemon.length; i++) //do the actual search here&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (pokemon[i][1].toLowerCase().includes(name.toLowerCase())) //converts to lowercase so that the search is case-insensitive&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; matchIndexes.push(i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; wnd.onload = function()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //now to populate the new page, similar to how it was done before&nbsp; &nbsp; &nbsp; &nbsp; itemList = wnd.document.getElementsByClassName("pd");&nbsp; &nbsp; &nbsp; &nbsp; console.log(matchIndexes);&nbsp; &nbsp; &nbsp; &nbsp; for (i = 0; i < itemList.length; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itemList[i].innerHTML = generateString(pokemon[matchIndexes[i]]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}但是,我还没有真正尝试过这个,所以它可能会或可能不会工作。如果没有,我会在处理程序的最开头添加一些虚拟日志以查看它是否被调用,然后添加一行console.log(itemList);以查看getElementsByClassName()调用是否找到任何内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript