![](/img/trans.png)
[英]Secure or enable the 'href' attribute of links with jQuery or Javascript
[英]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.