簡體   English   中英

無法訪問鏈接的href屬性

[英]Unable to access the href attribute of links

我想訪問某些鏈接的href屬性,如果它們包含某些字符串,請對其進行更改。 這是我當前的代碼:

var all_links = document.querySelectorAll('a');
for(var i = 0; i <= all_links.length; i++) {
   if(all_links[i].href.includes('test')) {
     all_links[i].href = 'something.com/?' + all_links[i].href;
   }
}

代碼不斷給我錯誤:

jquery.min.js:2 Uncaught TypeError: Cannot read property 'href' of undefined

但是,網頁上肯定有很多鏈接。 我可以使用以下命令在控制台中獲取所有鏈接:

console.log(all_links[i]);

為什么我不能訪問href屬性?

這是我關注的問題: 從錨(a)標簽獲取本地href值

您需要替換<=<因為數組索引為零。

for(var i = 0; i < all_links.length; i++)

或使用filter和forEach

Array.from(document.querySelectorAll('a'))
    .filter(({href}) => href.includes('test'))
    .forEach(link => link.href = `something.com/?${href}`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM