[英]document.getElementById doesn’t work
如果我寫的代碼2 不帶代碼1,則該代碼有效,並且顯示“ aaaaa”。
但是,如果我編寫代碼1 和代碼2,該代碼將無法正常工作。 它沒有向我顯示“ vvvaa”,沒有顯示給我任何東西(不是“ aaaaa”,也不是“ vvvaa”)。
為什么不起作用? ( document.getElementById
不會將信息發送到<div>
。)
代碼1:
document.getElementById('na').innerHTML = "vvvaa";
代碼2:
document.write("<div id='na'> aaaaa </div>");
完整代碼:( 頁面上唯一的內容)
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>
順序很重要。 在文檔中添加元素'na'
之前,您無法對其進行訪問。
您自然需要首先將元素添加到文檔中。 完成后,您可以通過類似getElementById()
函數來訪問它。
這個...
document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";
... 將工作。
您可以將此快捷方式更改為:
document.write("<div id='na'>vvvaa</div>");
我假設您的控制台說document.getElementById('na')
是未定義的,而innerHTML
不是未定義的方法。 這是由於在調用代碼時沒有這樣的元素引起的。 致命錯誤將停止任何進一步的javascript執行,在這種情況下,您將執行document.write
。
在嘗試通過document.getElementById
訪問元素之前,請先將其添加到document.getElementById
除非文本確實存在,否則您無法訪問它。 對於您的情況,您正在嘗試訪問當時還不存在的文本。 順序很重要。 代碼2應該排在最前面,代碼1應該排在最后。 首先寫文本,然后訪問它。
document.write
僅在timeago()
之后傳遞,因此在<div>
上不存在,因此在使用document.write
之后只需調用“ timerago”即可:
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
document.write("<div id='na'> aaaaa </div>");
timeago('1376743609');
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.