0

我已经动态创建了一个包含日期和时间的通用标题。目前它的行为和看起来都很好,但是一旦我删除了 document.write('.') 它就会消失。看来我需要在那里写任何形式的东西才能让 dateDiv 出现,即“。” 只是用于填充空间的随机字符。

//write date/time to div
var dateDiv = document.createElement('div');
dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ',     ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
dateDiv.id = 'dateTime';

//dateDiv disappears without a document.write() before being appended to the body. need to fix
document.write('.');

document.body.appendChild(dateDiv);

我还没有找到这个问题的答案,有人看到问题了吗?

4

1 回答 1

2

由于 loganfsmyth 暗示您的代码可能在文档未完全加载时被执行。尝试:

window.onload = function(){
    //write date/time to div
    var dateDiv = document.createElement('div');
    dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ',     ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
    dateDiv.id = 'dateTime';
    document.body.appendChild(dateDiv);
};

编辑:参见例如http://javascript.about.com/library/blonload.htm

于 2012-12-19T17:21:25.867 回答