[英]Javascript dynamically created div hidden unless document.write() is included
我已經動態創建了一個包含日期和時間的通用標頭。 目前它的行為和看起來非常好,但是一旦我刪除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);
我還沒有找到答案,有人看到了問題嗎?
正如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);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.