我正在尝试在同一页面上显示多个时钟。但是,querySelectorAll似乎没有这样做。我正在使用现代浏览器(已在Chrome和Safari中测试过)。我做错了什么?
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>
答案 0 :(得分: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);