2016-11-05 62 views
-2

我有以下代碼,但它不按我想的方式工作。如何更改鏈接中的URL使用Javascript

var myList = document.getElementsByTagName("a"); 
 
var url = "http://www.site2.com"; 
 

 
for (i = 0; i < myList.length; i++) { 
 
    url = url + myList[i]; 
 
    alert("the new link is " + url); 
 
    myList[i].setAttribute('href', url); 
 
}
<a href="/link1.html">link1</a> 
 
<a href="/link2.html">link2</a> 
 
<a href="/link3.html">link3</a> 
 
<a href="/link4.html">link4</a> 
 
<a href="/link5.html">link5</a>

如何得到這樣的結果:

<a href="http://www.site2.com/link1.html">link1</a> 
<a href="http://www.site2.com/link2.html">link2</a> 
<a href="http://www.site2.com/link3.html">link3</a> 
<a href="http://www.site2.com/link4.html">link4</a> 
<a href="http://www.site2.com/link5.html">link5</a> 
+1

你得到什麼樣的結果? –

+0

@LemuelBotha我剛剛注意到,我一遍又一遍地將內容添加到'url' ... haha​​haha ...但我感謝你的時間!謝謝! –

回答

2

獲取當前屬性值,然後與url字符串追加,同時設置屬性。

var myList = document.getElementsByTagName("a"); 
 
var url = "http://www.site2.com"; 
 

 
for (i = 0; i < myList.length; i++) { 
 
    myList[i].setAttribute('href', url + myList[i].getAttribute('href')); 
 
    //-----------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---- 
 
}
<a href="/link1.html">link1</a> 
 
<a href="/link2.html">link2</a> 
 
<a href="/link3.html">link3</a> 
 
<a href="/link4.html">link4</a> 
 
<a href="/link5.html">link5</a>

+1

非常感謝! ;) –

+1

@PauloDosSantos:很高興幫助:) –

1

獲得錨的href屬性,並添加到URL

var myList = document.getElementsByTagName("a"); 
var url = "http://www.site2.com"; 

for (i = 0; i < myList.length; i++) { 
    myurl = url + myList[i].getAttribute('href'); 
    //alert("the new link is " + url); 
    myList[i].setAttribute('href', myurl); 
} 

這裏正在撥弄
https://jsfiddle.net/wrycuoma/