我正在从 Javascript 生成 html 表并将其作为 InnerHTML 分配给 div 标签,但它给出了错误:
"Uncaught TypeError: Cannot set property 'innerHTML' of null"
<html>
<body>
<div class="fieldlist-vertical-title" style="color:white;left:0px;display:none;" id="rosterlegend">Some text</div>
<script>
function generateLegend()
{
var fullTable ='' fullTable='<Table><TR><Table><TR bgcolor=#FF5733><TD>MM</TD>
<TD>01:00 to 21:30</TD></TR></Table></TR></Table>'
document.getElementById('rosterlegend').innerHTML = fullTable
}
generateLegend();
</script>
</body>
</html>
Error : Uncaught TypeError: Cannot set property 'innerHTML' of null
最佳答案
尝试更改为类似的内容,以便我们确保 HTML DOM 首先已完成加载。
使用 ES6 模板字符串而不是普通字符串!
document.addEventListener('DOMContentLoaded', () => {
generateLegend();
});
function generateLegend() {
fullTable = `<Table>
<TR>
<Table>
<TR bgcolor=#FF5733>
<TD>MM</TD>
<TD>01:00 to 21:30</TD>
</TR>
<TR bgcolor=#FFFFFF>
<TD>EVVV</TD>
<TD>09:00 to 05:30</TD>
</TR>
</Table>
</TR>
</Table>`;
document.getElementById('rosterlegend').innerHTML = fullTable;
}
<div id="rosterlegend">
<div>
关于javascript - 错误为 "Cannot set property ' innerHTML' of null”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54415027/