我有以下代码,我在其中尝试迭代创建标签元素newDay(我附加newDayIcon并最终附加到newWeekSet:...console.log(dict); var newLine = document.createElement('div').classList.add('list-group-item'); var newButton = document.createElement('div').classList.add('add-button'); var newTemp = document.createElement('a'); var newName = document.createElement('a').classList.add('name-font'); var newWeekSet = document.createElement('div').classList.add('right-align'); Object.entries(dict).forEach(function([key, value]) { console.log(key, value); var newDay = document.createElement('label').classList.add('day-font'); var newDayIcon; console.log(newDay); newDay.textContent = key.charAt(0); if (value) { newDayIcon = document.createElement('i').classList.add('far', 'fa-check-circle', 'fa-xs') newDayIcon.style.color = 'Blue'; } else { newDayIcon = document.createElement('i').classList.add('far', 'fa-times-circle', 'fa-xs') newDayIcon.style.color = 'Orange'; } newDay.appendChild(newDayIcon); newWeekSet.appendChild(newDay); }); var newMoveIcon = document.createElement('i').classList.add('fas', 'fa-bars'); newButton.id = 'schedule-'+i++; newLine.append(newButton, newName, newWeekSet, newMoveIcon); dashboard.appendChild(newLine);}具有以下电流输出: Friday: null, Monday: Object { EndTime: "12:50 A.M.", StartTime: "12:55 A.M." }, Saturday: null, Sunday: Object { EndTime: "12:50 A.M.", StartTime: "12:55 A.M." }, Thursday: null, Tuesday: null, Wednesday: null}"Sunday" Object { EndTime: "12:55 A.M.", StartTime: "12:59 A.M."}undefinedTypeError: undefined is not an object (evaluating 'newDay.textContent = key.charAt(0)') 我似乎无法弄清楚为什么newDay不能以这种方式创建元素 - 是否有特殊原因这不起作用?
1 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
我想我看到了这个问题。document.createElement('label').classList.add('day-font');不返回值。无论您在哪里使用结果,classList.add本质上都是将 var 分配给undefined.
我在你的脚本中的很多地方都看到了这种模式。我建议先创建元素并将值分配给 var,然后再尝试像这样操作它:
var newDay = document.createElement('label');
newDay.classList.add('day-font');
// do even more things to newDay if you want.
无论您在哪里创建新元素,然后稍后尝试更新该元素,您都需要像这样将步骤分开。
如果您有任何疑问,请告诉我!
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消