javascript - Javascript not operating on loaded elements
问题描述
I am trying to understand grid layouts so I wrote some js to recursively color each element on the page to expose each grid tile.
The problem
Every few refreshes some of the tiles don't get colored. I figured this was some kind of loading error so instead of running the code immediately I decided to run it in window.onload
. That didn't change anything.
I even wrote a piece of code to print the uncolored elements to the console. I run that code in the same loop where individual elements are painted and expected nothing to be logged, to my surprise the color is generated, the element is created, and still the element remains uncolored!
Plea
Can someone tell me what's going on here? It's not very important in this application but this goes against everything I know about how js operates, and it would be helpful to extend my understanding. Thanks!
P.S. Demo
I added this little demo and the problem happens here too. You will need to run the code a couple times to see the error, I wrote another piece of code that prints the uncolored element to the console so you can't miss it!
let colorize = (elements) => {
for (let e of elements) {
let color = '#' + Math.floor(Math.random() * 16777215).toString(16);
e.style["background-color"] = color;
checkcolor(e, color);
colorize(e.children);
}
}
let checkcolor = (e, color) => {
if (!e.style['background-color']) {
console.log(e, color);
}
}
window.onload = () => colorize(document.querySelector("html").children);
body {
height: calc(100vh - 3px);
display: grid;
grid-template-rows: repeat(5, minmax(10px, 100px));
/* grid-template-columns: 1; */
grid-auto-flow: row;
}
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
<div>55</div>
解决方案
以下是其中一个结果的示例console.log
:
<div>55</div> #43b0f
这应该给你的想法 - 生成的字符串只有 5 个字符(或更少),而不是 6 个,所以它不是有效的十六进制颜色。当生成的数字具有前导零时,就会发生这种情况。
解决它的一种方法是padStart
使用零的数字:
const colorize = (elements) => {
for (let e of elements) {
let color = '#' +
Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, '0');
e.style["background-color"] = color;
colorize(e.children);
}
}
colorize(document.querySelectorAll('div'));
body {
height: calc(100vh - 3px);
display: grid;
grid-template-rows: repeat(5, minmax(10px, 100px));
/* grid-template-columns: 1; */
grid-auto-flow: row;
}
<div>11</div>
<div>22</div>
<div>33</div>
<div>44</div>
<div>55</div>
推荐阅读
- c++ - 有符号长整数的含义
- swift - 斯威夫特:计时器有最高速度吗?
- javascript - ReactJS 中的 onChange 事件处理程序
- docker - 我将如何创建 Gradle 应用程序的 docker 容器?
- javascript - 有什么方法可以在按下键时检测到碰撞?
- c++ - 如何在不共享单个变量的情况下计算线程池中已完成的作业?
- javascript - 将 JS 对象关联到 HTML ID
- google-analytics - 如果我在查询中应用数据过滤器,PowerBI 通过连接 Google Analytics 显示错误数据
- javascript - 如何在 NodeJS 中使用 MongoDB 查询进行聚合
- typescript - 在导入的模块(jsonrpc-lite)中声明类型时如何使用类型保护?