1. 程式人生 > >html中引入公用的功能性html(避免重複性程式碼)

html中引入公用的功能性html(避免重複性程式碼)

<!DOCTYPE html>
<html>
<head>
    <title>自動引入其他HTML標籤</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="zh-CN" />
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>

<div class="include" file="header.html">需要引入的</div>

<div>自身部分</div>
<div class="include" file="footer.html">需要引入的</div>
<script type="text/javascript">
//三種不同方式引入頁面,載入的檔案內容寫入到當前標籤裡面並移除當前標籤<div class="include" ></div>
//基於ajax的get請求
$(".include").each(function() {
    var file = $(this).attr("file");
    if(!!file) {
        var thisObj = $(this);
        $.get(file, function(html) {
            thisObj.after(html).remove();
        });
    }
});
//基於iframe請求的實現是要使用jQuery偽造一個隱藏的iframe標籤出來請求檔案內容,獲取後移除它
$(".include").each(function(){
    var file = $(this).attr("file");
    if(!!file) {
        var $includeObj = $(this);
        $("<iframe style='display:none'>").attr("src", file).attr("name", file).appendTo($("body")).load(function(){
            $includeObj.after($(window.frames[file].document).text()).remove();
            $(this).remove();
        });
    }
});
//使用jQuery的load方法
$(".include").each(function(){
    if(!!$(this).attr("file")) {
        var $includeObj = $(this);
        $(this).load($(this).attr("file"), function(html){
            $includeObj.after(html).remove();    //載入的檔案內容寫入到當前標籤後面並移除當前標籤
        })
    }
});
</script>
</body>
</html>