代碼主要理解3個參數:createElement、createTextNode、appendChild。這3個JS參數分別是創建元素、創建字符、追加節點。代碼原理:循環頁面段落標簽<p>,創建連接元素<a>,創建要顯示的連接字符,用SetAttribute定義元素a的樣式和連接地址。在循環標簽<p>後追加創建的元素<a>。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xHtml">
<head>
<meta http-equiv="Content-Type" content="text/Html; charset=gb2312" />
<title>無標題文檔</title>
<style>
.test {color:#fff;margin-left:18px;}
</style>
</head>
<body>
<p>如何在文章的每段後面加入一行帶連接的隱藏文字?</p>
<p>如何在文章的每段後面加入一行帶連接的隱藏文字?</p>
<p>如何在文章的每段後面加入一行帶連接的隱藏文字?</p>
<script>
function test()
{
var myP = document.getElementsByTagName("p");
for(var i=0;i<myP.length;i++)
{
var createLink = document.createElement("a");
createLink.setAttribute("class","test");
createLink.setAttribute("href","http://www.webjx.com/");
createLink.setAttribute("target","new");
var createText = document.createTextNode("網頁教學網");
createLink.appendChild(createText);
myP[i].appendChild(createLink);
}
}
window.onload = function() {test();}
</script>
</body>
</Html>