2015-04-25 69 views
1

我試圖在同一頁上顯示多個時鐘。但是,querySelectorAll似乎沒有這樣做。我使用的是現代瀏覽器(已經在Chrome和Safari中測試過)。我究竟做錯了什麼?querySelectorAll在多個類不工作

JS代碼:

/*global document, window */ 
function checkTime(i) { 
    'use strict'; 
    if (i < 10) { 
     i = "0" + i; 
    } 
    return i; 
} 
function a() { 
    'use strict'; 
    var oct = ["0", "1", "2", "3", "4", "5", "6", "7"], 
     octtime, 
     oct1, 
     oct2, 
     oct3, 
     oct4, 
     oct5, 
     oct6, 
     octvalue, 
     point = ".", 
     now = new Date(), 
     hours = now.getHours(), 
     minutes = now.getMinutes(), 
     seconds = now.getSeconds(), 
     h = checkTime(hours), 
     m = checkTime(minutes), 
     s = checkTime(seconds), 
     totsecs = [hours * 3600 + minutes * 60 + seconds + (now.getTime() % 1000)/1000]; 
    octtime = Math.floor(totsecs/(86400/262144)); 
    oct1 = Math.floor(octtime/32768); 
    octtime -= 32768 * oct1; 
    oct2 = Math.floor(octtime/4096); 
    octtime -= 4096 * oct2; 
    oct3 = Math.floor(octtime/512); 
    octtime -= 512 * oct3; 
    oct4 = Math.floor(octtime/64); 
    octtime -= 64 * oct4; 
    oct5 = Math.floor(octtime/8); 
    octtime -= 8 * oct5; 
    oct6 = octtime; 
    octvalue = point + oct[oct1] + oct[oct2] + oct[oct3] + oct[oct4] + oct[oct5] + oct[oct6]; 
    document.querySelectorAll(".c").innerHTML = h + ":" + m + ":" + s; 
    document.querySelectorAll(".d").innerHTML = octvalue; 
    window.setTimeout(a); 
} 
window.onload = a; 

HTML代碼:

<div class="a"> 
<table> 
<tr> 
<td><b>Regular Time</b> 
<td><b>Octal Time</b> 
<tr> 
<td class="c">JS problem 
<td class="d">JS problem 
</table> 
</div> 
<br> 
<div class="a"> 
<table> 
<tr> 
<td><b>Regular Time</b> 
<td><b>Octal Time</b> 
<tr> 
<td class="c">JS problem 
<td class="d">JS problem 
</table> 
</div> 
<script src="/1.js"></script> 

測試頁:http://www.gloryhood.com/ztest.html

回答

2

這是因爲querySelectorAll返回nodeList不是單一節點元素,所以你需要遍歷並設定值

function setHtmlForByClass(clazz, html) { 
    var nodes = document.querySelectorAll('.' + clazz) 
    for (var i = 0; i < nodes.length; i++) { 
     nodes[i].innerHTML = html; 
    } 
} 
setHtmlForByClass('c', h + ":" + m + ":" + s); 
setHtmlForByClass('d', octvalue);