从循环获取变量到函数
getting variable from loop to function
所以我正在研究 discord bot 仪表板,我正在尝试制作重定向按钮以转到 discord 服务器用户选择。所以我正在尝试制作动态地址,例如:http://localhost:3000/dash/discord/servers/${guildid},但是当我获得公会 ID 并尝试将其传递给 button.onclick 函数时,我只是得到 3 而不是前。 1,2,3。一切都在循环中,所以我有点困惑。请帮忙!
所有代码都在 html 文件中 - 脚本
循环代码:
document.addEventListener('DOMContentLoaded',函数(){
for (var i = 0; i < guildsLength; i++) {
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = Guildss[i] + " ID: " + IDs[i];
button.className = 'btn-styled';
button.id = 'b1';
button.onclick = function (){
location.href = `http://localhost:3000/dash/discord/servers/${IDs[i]}`
}
document.body.appendChild(button);
}
}, false);
由于 javascript closures,您总是获得最后的 i
值。当调用 onclick 方法时,它访问在其外部函数中定义的 i
变量,此时 i
具有 for
循环完成时的值。
您可以使用 <a>
标签并将 url 存储在 href
属性中。这样你就不需要任何回调,如果你愿意,你可以将锚点设置为按钮。
所以我正在研究 discord bot 仪表板,我正在尝试制作重定向按钮以转到 discord 服务器用户选择。所以我正在尝试制作动态地址,例如:http://localhost:3000/dash/discord/servers/${guildid},但是当我获得公会 ID 并尝试将其传递给 button.onclick 函数时,我只是得到 3 而不是前。 1,2,3。一切都在循环中,所以我有点困惑。请帮忙!
所有代码都在 html 文件中 - 脚本
循环代码:
document.addEventListener('DOMContentLoaded',函数(){
for (var i = 0; i < guildsLength; i++) {
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = Guildss[i] + " ID: " + IDs[i];
button.className = 'btn-styled';
button.id = 'b1';
button.onclick = function (){
location.href = `http://localhost:3000/dash/discord/servers/${IDs[i]}`
}
document.body.appendChild(button);
}
}, false);
由于 javascript closures,您总是获得最后的 i
值。当调用 onclick 方法时,它访问在其外部函数中定义的 i
变量,此时 i
具有 for
循环完成时的值。
您可以使用 <a>
标签并将 url 存储在 href
属性中。这样你就不需要任何回调,如果你愿意,你可以将锚点设置为按钮。