script let bd = documentquerySelectorbody; let num = 97; forlet i = 0;i 26;i++ let d = documentcreateElementdiv; let str = StringfromCharCodenum; dinnerHTML=str; bdonkeypress=key+st
以上代码有以下问题:
-
bd.onkeypress="key("+str+")";这一行代码应该写成bd.onkeypress = function() { key(str); },即给bd.onkeypress赋值一个匿名函数。 -
在
key函数中,变量num1没有被使用,应该将它改为num。 -
在
key函数中,对num进行递增操作后,没有重置为97,导致循环无法正确执行。
修正后的代码如下:
<script>
let bd = document.querySelector('body');
let num = 97;
for (let i = 0; i < 26; i++) {
let d = document.createElement('div');
let str = String.fromCharCode(num);
d.innerHTML = str;
bd.onkeypress = function() { key(str); }
d.id = str;
bd.appendChild(d);
num++;
}
function key(o) {
let num = 97;
for (let i = 0; i < 26; i++) {
console.log(o)
let str = String.fromCharCode(num);
if (o == str) {
document.getElementById(o).style.background = "red";
}
num++;
}
}
</script>
``
原文地址: https://www.cveoy.top/t/topic/iqmw 著作权归作者所有。请勿转载和采集!