为什么我会收到:未捕获的TypeError:无法读取属性< innerHTML'未定义? 我想从一个"任务"获得日,月和年。所以我可以计算出任务剩余的天数,但我得到了这个错误。
<div class="task" id="task">
<ul>
<li class="title" id="@ta.Id"><div class="complete"></div>@ta.Title</li>
<li class="body"><b>Project: </b>@ta.Description</li>
<li>Hand In: @ta.Dia/@ta.Mes/@ta.Año</li>
<li class="leftion">Days left: </li>
<li class="day" style="display: none">@ta.Day</li>
<li class="month" style="display: none">@ta.Month</li>
<li class="year" style="display: none">@ta.Year</li>
</ul>
</div>
<script language="javascript" type="text/javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var firstDate = new Date(yyyy, mm, dd);
var gio = document.getElementsByClassName("task");
var lele = document.getElementsByClassName("leftion");
for (var i = 0; i <= gio.length; i++) {
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var day= document.getElementsByClassName("day")[i].innerHTML;
未捕获的TypeError:无法读取属性&lt; innerHTML&#39;未定义的
var month = document.getElementsByClassName("month")[i].innerHTML;
var year= document.getElementsByClassName("year")[i].innerHTML;
var secondDate = new Date(year, month, day);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
lele[i].innerHTML = diffDays;
}
</script>
答案 0 :(得分:0)
您的html
中可能有.task
个节点而不是.day
个节点
如果您只在当前.task
节点的节点中查找当天,您将有更多机会找到您的错误并避免许多奇怪的行为:
var gio = document.getElementsByClassName("task");
//...
for (var i = 0; i <= gio.length; i++) {
//...
var taskNode = gio[i];
var day = taskNode.getElementsByClassName("day")[0].innerHTML;
请参阅gio[i].getElementsByClassName
的使用,而不是document.getElementsByClassName
答案 1 :(得分:-1)
使用循环for (var i = 0; i <= gio.length; i++) {...}
时,gio.length
=== 1,这意味着循环将运行两次。
因此,当i
=== 1时,document.getElementsByClassName("day")[i]
为undefined
,因为您只有一天&#34;天&#34; class element。
将i <= gio.length
更改为i < gio.length
或一般重构代码。