我有以下代码,但它没有像我想象的那样工作。
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>
答案 0 :(得分: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)