簡體   English   中英

如何使用JavaScript編輯外部鏈接

[英]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.

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