简体   繁体   English

为什么 js 中的 getAttribute() 会给出错误:?

[英]Why is getAttribute() in js giving error :?

following is the code i wrote.以下是我写的代码。 If i change code in for loop to i<len-1 then its working just fine except for last link But if i keep it like i<len, it isn't working for any link.如果我将 for 循环中的代码更改为 i<len-1,那么它工作得很好,除了最后一个链接但是如果我像 i<len 一样保持它,它不适用于任何链接。

const allLists = document.querySelectorAll("a:link");
var len = allLists.length;

for (var i = 0; i < len; i++) {
  allLists[i].addEventListener("click", function (e) {
    e.preventDefault();
    const href = allLists[i].getAttribute("href");
    console.log(href);
    if (href == "#") {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }
  });
}

Error: script.js:33 Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute') at HTMLAnchorElement.错误:script.js:33 Uncaught TypeError:无法在 HTMLAnchorElement 处读取未定义的属性(读取“getAttribute”)。

Because i variable by len after your looping因为i在循环后由len变量

Then, each time the click event is called, the code to be run will always be:那么,每次点击事件被调用时,要运行的代码总是:

const href = allLists[len].getAttribute("href");

This problem is a closure problem you can see more here这个问题是一个closure问题,你可以在这里看到更多

The revised code will look like : (change var to let )修改后的代码将如下所示:(将var更改为let

 const allLists = document.querySelectorAll("a:link"); var len = allLists.length; for (let i = 0; i < len; i++) { allLists[i].addEventListener("click", function (e) { e.preventDefault(); const href = allLists[i].getAttribute("href"); console.log(href); if (href == "#") { window.scrollTo({ top: 0, behavior: "smooth", }); } }); }
 <a href="1">1</a> <a href="2">2</a> <a href="3">3</a> <a href="4">4</a>

As stated in the Mozilla developer docs “ querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results.”正如Mozilla 开发人员文档中所述,“querySelectorAll() 的行为与大多数常见的 JavaScript DOM 库不同,这可能会导致意外结果。”

So I would suggest following the docs and code a 'forEach' loop instead of a 'for' loop.所以我建议遵循文档并编写一个“forEach”循环而不是一个“for”循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM