有人能告诉我为什么这段代码会冻结ie8?它应该生成输入字段。在firefox,safari,chrome中它可以工作,但是当我按下生成按钮时它会冻结
var monthNames = [ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" ];
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('datastart').value);
var endDate = new Date(document.getElementById('dataend').value);
if (startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
// inclusiv dataend
endDate.setMonth(endDate.getMonth() + 1);
// start with startDate; loop until we reach endDate
for (var dt = startDate;
! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() );
dt.setMonth( dt.getMonth() + 1 )
) {
monthlyEntries.appendChild( document.createTextNode(
monthNames[dt.getMonth()] + " " + String(dt.getFullYear()).substring(2)
) );
var textElement = document.createElement('input');
var textElement2 = document.createElement('input');
var textElement3 = document.createElement('input');
textElement.setAttribute('type', 'text');
//textElement.setAttribute('name', 'entry['+ monthNames[dt.getMonth()] + + String(dt.getFullYear()).substring(2) + ']');
textElement.setAttribute('name', 'entry[]');
textElement2.setAttribute('type', 'hidden');
textElement2.setAttribute('name', 'luna[]');
textElement2.setAttribute('value', '' + monthNames[dt.getMonth()] + '');
textElement3.setAttribute('type', 'hidden');
textElement3.setAttribute('name', 'an[]');
textElement3.setAttribute('value', '' + String(dt.getFullYear()) + '');
monthlyEntries.appendChild(textElement);
monthlyEntries.appendChild(textElement2);
monthlyEntries.appendChild(textElement3);
// adauga br
// monthlyEntries.appendChild(document.createElement("br"));
}
return null;
}
答案 0 :(得分:0)
如果您的任何一个日期字符串格式不正确,IE8将不会在您测试时返回"Invalid Date"
。相反,它将返回NaN
。你也需要测试它。您可以在IE8中的this jsFiddle中看到这一点。您可以通过更改为此来防范:
if (startDate == "Invalid Date" || endDate == "Invalid Date" ||
isNaN(startDate) || isNaN(endDate)) { return null; }
其次你的for循环很容易成为无限循环:
// start with startDate; loop until we reach endDate
for (var dt = startDate;
! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() );
dt.setMonth( dt.getMonth() + 1 )
)
如果dt
大于endDate
,那么for
循环将永远不会结束。写一个更安全的方式就是这样:
// start with startDate; loop until we reach endDate
// make sure endDate is always after startDate
if (endDate < startDate) {
var temp = endDate;
startDate = endDate;
endDate = temp;
}
for (var dt = startDate;
! ( dt.getFullYear() == endDate.getFullYear() && dt.getMonth() == endDate.getMonth() );
dt.setMonth( dt.getMonth() + 1 )
)
答案 1 :(得分:0)
您也可以执行&lt; =而不是negated strict ==。