gpt4 book ai didi

javascript - 使用 object.keys 和 foreach 使用文档按 id 获取元素来显示数据时出错

转载 作者:行者123 更新时间:2023-11-28 17:15:19 24 4
gpt4 key购买 nike

目前我正在尝试让我的 js 脚本显示对象 udata 中的数据。

我不断收到错误:

Uncaught TypeError: Cannot read property 'innerHTML' of null.

我已经使用字符串 (var str = 'test') 进行了测试,并且没有给出错误,但是一旦我切换到使用 itemValue 作为 id检查一下,我收到错误。我尝试使用 .toString() 使键成为字符串,但这也不起作用。 不知道该怎么办。 != null 语句应该使 foreach 避免在对象键不与 html 中的 id 对应的少数情况下进行 null 操作。

如果有任何帮助,我将不胜感激!

if(localStorage.udata != null){
var udata = JSON.parse(localStorage.getItem('udata'));

Object.keys(udata).forEach(function (itemValue) {
if(document.getElementById(itemValue).innerHTML != null)
document.getElementById(itemValue).innerHTML = udata[itemValue];
});

最佳答案

您的检查实际上导致了错误。您必须检查是否

 document.getElementById(itemValue)

null,尝试访问.innerHTML会导致错误。

关于javascript - 使用 object.keys 和 foreach 使用文档按 id 获取元素来显示数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53602049/

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