JavaScript 中的 For 循环无法正常工作
For Loop in JavaScript is not working correctly
const box = document.querySelectorAll(".box");
console.log(box.length);
const direction = [
"top-start",
"bottom-start",
"left-start",
"right-start",
"top-center",
"bottom-center",
"left-center",
"right-center",
"top-end",
"bottom-end",
"left-end",
"right-end"
];
box.forEach((el, index) => {
for (let i = 0; i < direction.length; i++) {
CreateTooltip(el, direction[index], "Hello, World!");
}
});
上面提到的代码渲染 144
DOM
中的工具提示,我只想要 12 个,每个应该有不同的方向。我不明白为什么这个循环不起作用!我试图在 for
循环中添加 forEach
循环,但问题仍然相同。
注意 正如你们中的一些人所问,我粘贴了我的全部代码。希望它能帮助你,然后你会帮助我。
如果您使用 Queryselectorall ,如果它是 class 使用点,或者如果您使用 id 使用 #
const box = document.querySelectorAll('.box');
可以这样传入每个元素的索引,从方向数组中获取对应的值
box.forEach((element, index) => {
CreateTooltip(element, direction[index], 'Hello, World!');
})
根据你所说的,即想要 12 个工具提示(与 direction
索引计数相同)但得到 144 个工具提示 (144/12 = 12) 你应该有 12 个元素 .box
class 在您的页面中。问题出在您的查询选择中。
const box = document.querySelectorAll('.box');
console.log(box.length); // this should show 12
您需要做的是为您的元素设置一个 ID 或为框(此时为数组)创建一个循环并分别为它们中的每一个执行您的 CreateTooltip
逻辑。
注意: 我建议您在测试环境(为测试您的代码而创建的单独文件)中仅使用一个 .box
元素来测试您的 CreateTooltip
,您使用的库可能不支持对单个元素多次调用 CreateTooltip
,这可能是您获得 144 个元素而不是 12 个元素的原因。
您的代码运行良好,因为您正在迭代框列表并且在其中有另一个迭代,所以您的代码的结果将始终是(框数)*(方向数)= 144。 .
因此,您可以通过下面给出的索引号操纵一个列表和其他列表来仅在框或方向上进行迭代。
$(box).each(function(i,v){console.log(direction[i])})
const box = document.querySelectorAll(".box");
console.log(box.length);
const direction = [
"top-start",
"bottom-start",
"left-start",
"right-start",
"top-center",
"bottom-center",
"left-center",
"right-center",
"top-end",
"bottom-end",
"left-end",
"right-end"
];
box.forEach((el, index) => {
for (let i = 0; i < direction.length; i++) {
CreateTooltip(el, direction[index], "Hello, World!");
}
});
上面提到的代码渲染 144
DOM
中的工具提示,我只想要 12 个,每个应该有不同的方向。我不明白为什么这个循环不起作用!我试图在 for
循环中添加 forEach
循环,但问题仍然相同。
注意 正如你们中的一些人所问,我粘贴了我的全部代码。希望它能帮助你,然后你会帮助我。
如果您使用 Queryselectorall ,如果它是 class 使用点,或者如果您使用 id 使用 #
const box = document.querySelectorAll('.box');
可以这样传入每个元素的索引,从方向数组中获取对应的值
box.forEach((element, index) => {
CreateTooltip(element, direction[index], 'Hello, World!');
})
根据你所说的,即想要 12 个工具提示(与 direction
索引计数相同)但得到 144 个工具提示 (144/12 = 12) 你应该有 12 个元素 .box
class 在您的页面中。问题出在您的查询选择中。
const box = document.querySelectorAll('.box');
console.log(box.length); // this should show 12
您需要做的是为您的元素设置一个 ID 或为框(此时为数组)创建一个循环并分别为它们中的每一个执行您的 CreateTooltip
逻辑。
注意: 我建议您在测试环境(为测试您的代码而创建的单独文件)中仅使用一个 .box
元素来测试您的 CreateTooltip
,您使用的库可能不支持对单个元素多次调用 CreateTooltip
,这可能是您获得 144 个元素而不是 12 个元素的原因。
您的代码运行良好,因为您正在迭代框列表并且在其中有另一个迭代,所以您的代码的结果将始终是(框数)*(方向数)= 144。 .
因此,您可以通过下面给出的索引号操纵一个列表和其他列表来仅在框或方向上进行迭代。
$(box).each(function(i,v){console.log(direction[i])})