如何在查询选择器-JS中使用变量?
我在做什么错? 有7张图片,具有从“ IMG1”到“ IMG7”的预制ID
function changeWidth() {
let b = 50
let k = 0
let l = `"#img${(k + 1)}"`;
for (let k = 0; k < 7; k++)
document.querySelector("l").width = `${(b = b + 50)}`;
}
What am I doing wrong?
there are 7 pictures with pre-made IDs from "img1" to "img7"
function changeWidth() {
let b = 50
let k = 0
let l = `"#img${(k + 1)}"`;
for (let k = 0; k < 7; k++)
document.querySelector("l").width = `${(b = b + 50)}`;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
评论涵盖了基础知识;将模板在循环中移动,从模板内部删除引号,并参考无引号的变量。
但是您实际上可以简化以不使用循环中的索引,
k
1
而不是0
避免加法和使用getElementById
比QuerySelector
更有效。The comment covers the basics; move the template literal inside the loop, remove quotes from inside your template literal, and refer to the variable without quotes.
But you can actually simplify to not use any variables except the index in the loop, start
k
at1
instead of0
to avoid addition, and usegetElementById
which is more efficient thanquerySelector
.