這段代碼主要需要理解三個參數:createElement、createTextNode、appendChild。這三個 JS 方法分別對應「創建元素」、「創建文字節點」、「追加節點」。
代碼原理是:遍歷頁面上的段落標籤 <p>,創建一個連結元素 <a>,再創建要顯示的連結文字,用 setAttribute 定義 a 元素的樣式與連結位址,最後把創建好的 <a> 追加到每個 <p> 之後。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://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","https://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>
透過 window.onload 觸發 test(),遍歷所有段落並在每個段落末尾插入一個統一样式的連結,就能輕鬆為整篇文章的每一段自動加上帶連結的浮水印式文字。