如何在查询选择器-JS中使用变量?

发布于 2025-01-28 22:16:22 字数 323 浏览 3 评论 0原文

我在做什么错? 有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

活泼老夫 2025-02-04 22:16:22

评论涵盖了基础知识;将模板在循环中移动,从模板内部删除引号,并参考无引号的变量。

function changeWidth() {
  let b = 50
  for (let k = 0; k < 7; k++) {
    let l = `#img${(k + 1)}`;
    document.querySelector(l).width = `${(b = b + 50)}`;
  }
}

但是您实际上可以简化以不使用循环中的索引,k 1而不是0避免加法和使用getElementByIdQuerySelector更有效。

function changeWidth() {
  for (let k = 1; k <= 7; k++) {
    document.getElementById(`img${k}`).width = `${50 + 50 * k}`;
  }
}

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.

function changeWidth() {
  let b = 50
  for (let k = 0; k < 7; k++) {
    let l = `#img${(k + 1)}`;
    document.querySelector(l).width = `${(b = b + 50)}`;
  }
}

But you can actually simplify to not use any variables except the index in the loop, start k at 1 instead of 0 to avoid addition, and use getElementById which is more efficient than querySelector.

function changeWidth() {
  for (let k = 1; k <= 7; k++) {
    document.getElementById(`img${k}`).width = `${50 + 50 * k}`;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文