Show toolbar

2011年10月30日 星期日

JavaScript insertBefore insertAfter cloneNode

標題:使用JavaScript在目標前後插入或包覆標籤
JavaScript (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image</title>
<script type="text/javascript">
function before() { //在img前插入
    var image = document.getElementById('myimg');
    var alink = document.createElement('a');
    alink.appendChild(document.createTextNode('Google'));
    alink.href = "http://www.google.com/";
    image.parentNode.insertBefore(alink, image); //在目標前插入
}
function wrap() { //包覆img
    var image = document.getElementById('myimg');
    var alink = document.createElement('a');
    alink.href = "http://www.google.com/";
    alink.appendChild(image.cloneNode(true)); //克隆一目標
    image.parentNode.replaceChild(alink, image); //取代舊有目標
}
function after() { //在img後插入
    var image = document.getElementById('myimg');
    var alink = document.createElement('a');
    alink.appendChild(document.createTextNode('Google'));
    alink.href = "http://www.google.com/";
    if(image.parentNode.lastChild == image) { //當目標為最後一個
        image.parentNode.appendChild(alink);
    } else { //當目標在中間
        image.parentNode.insertBefore(alink, image.nextSibling);
    }
}
</script>
</head>
<body>
<button onClick="before()">Before</button>
<button onClick="wrap()">Warp</button>
<button onClick="after()">After</button>
<img id="myimg" src="example.jpg" />
</body>
</html>
範例:




說明:
使用insertBefore、insertAfter、cloneNode不同方式插入新標籤, 針對上一篇文章建立範例程式, 並增加after及wrap之範例供學習。

1 則留言:

  1. 如果不考慮IE的話,其實可以參考
    http://www.w3.org/TR/html5/apis-in-html-documents.html#insertadjacenthtml

    回覆刪除