[英]How to edit external links with javascript
我想编辑类示例中的所有外部链接
<div class='main'>
<a href='http://test1.com'>link1</a>
<a href='http://test2.com'>link1</a>
<a href='http://test3.com'>link1</a>
</div>
我想编辑主类中的所有链接,并在链接之前添加另一个这样的链接
<div class='main'>
<a href='http://example.com/search=http://test1.com'>link1</a>
<a href='http://example.com/search=http://test2.com'>link2</a>
<a href='http://example.com/search=http://test3.com'>link3</a>
</div>
对不起我的英语不好
如果每个链接都有它自己的ID,例如
<a id="link1" href='http://test1.com'>link1</a>
然后试试这个
var currentAddress = document.getElementByID("link1").attr("href")
document.getElementByID("link1").attr("href", "http://example.com/search=" + currentAddress)
您可以使用document.querySelectorAll('.main a')
获取所有链接,对其进行迭代,然后在每个链接的href上使用replace()
将缺少的部分添加到href中。
var links = document.querySelectorAll('.main a'); for(var i=0; i<links.length; i++){ links[i].href = links[i].href.replace("http://", "http://example.com/search=http://"); }
<div class='main'> <a href='http://test1.com'>link1</a> <a href='http://test2.com'>link1</a> <a href='http://test3.com'>link1</a> </div>
您应该能够通过x路径规范使用javascript(如果可以访问jQuery,则可以使用jQuery)来获取“ a”标签的集合。 一旦有了集合,您应该可以遍历集合并设置新值。
这是有关x路径的一些信息。
https://www.w3schools.com/xml/xpath_examples.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.