为了账号安全,请及时绑定邮箱和手机立即绑定

在新窗口中使用 javascript 更改 innerHTML

在新窗口中使用 javascript 更改 innerHTML

Smart猫小萌 2023-03-10 15:09:30
我正在尝试使用下面的代码通过 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() 函数,为了澄清,在其他地方工作正常,即使在最坏的情况下也不可能输出空字符串。至少它会输出一些我可以在检查器中看到的字符。任何帮助,将不胜感激。
查看完整描述

1 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

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()调用是否找到任何内容。


查看完整回答
反对 回复 2023-03-10
  • 1 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号