1. 程式人生 > >案例十一 、使用jQuery動態追加頁面資料以及事件委託

案例十一 、使用jQuery動態追加頁面資料以及事件委託

我們要執行的任務是頁面起初有一部分圖片,我們在底下有一個More Photos的連結,點選後,向當前頁面後加載一部分圖片,再點選該連結,繼續載入,直到將我們列出的頁面載入完成,此時該連結也消失了。

首先效果圖如下:
這裡寫圖片描述
這個只截取了最底下的一部分頁面。在滑鼠懸停在圖片上時,還會有文字出現,滑鼠移出時文字消失。
我們現在要做的就是點選底下的MorePhotos連結時,再載入一部分資料,然後再點選在載入一部分資料,直到資料載入完。
首先body中程式碼如下:

<div id = "container">
<h1> Photo Gallery</h1>

<div
id = "gallery"> <div class = "photo"> <img src = "./images/1.jpg"> <div class = "details"> <div class = "description">The Cullin Mountains, Isle of skye ....</div> <div class = "date">12/24/2000</div> <div
class = "photographer"> Alasdair Dougall</div> </div> </div> <div class = "photo"> <img src = "./images/2.jpg"> <div class = "details"> <div class = "description">The Cullin Mountains, Isle of skye.... </div> <div
class = "date">12/24/2000</div> <div class = "photographer"> Alasdair Dougall</div> </div> </div> <div class = "photo"> <img src = "./images/3.jpg"> <div class = "details"> <div class = "description">The Cullin Mountains, Isle of skye.... </div> <div class = "date">12/24/2000</div> <div class = "photographer"> Alasdair Dougall</div> </div> </div> . . . . //若干圖片 </div> <div class = "link"><a id = "more-photos" href = "1.html"> More Photos &gt;&gt;</a></div> </div>

然後在同一根目錄下寫幾個HTML程式碼片段,用於載入。

如,我這有一個1.html程式碼如下

<div class = "photo">
        <img src = "./images/1.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

    <div class = "photo">
        <img src = "./images/2.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/3.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/4.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/5.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/6.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

在這個HTML片段中我引入了6個圖片。其他的片段如2.html等等都可以仿照上面的這個來寫。在定義好了許多個HTML片段後,利用jQuery進行動態追加資料。

<script>
    $(document).ready(function(){
    //首先定義一個變數來記錄當前是多少頁
        var pageNum = 1;

        //給連結新增點選事件
        $("#more-photos").click(function(event){
            event.preventDefault();
            var $link = $(this);

            //獲得當前所點連結的url
            var url = $link.attr('href');

            //如果該連結的url存在,進行頁面追加
            if(url){
                $.get(url, function(data){
                    $("#gallery").append(data);
                });

        pageNum ++;
    //總共有十個片段要追加,名稱分別為1.html,2.html ...10.html
        噹噹前頁面的總數小於總數時,進行連結更新。
        if(pageNum < 10){
            $link.attr('href', './'+pageNum+'.html');
                }

        //當將所有片段追加完成後,移除連結。
            else{
                $link.remove();
            }
            }
        })
    });

以上的程式碼就可以進行動態的向頁面追加資料了。

但是在谷歌的瀏覽器中會出現以下的錯誤:

jquery.js:8475 XMLHttpRequest cannot load file:///C:/Users/%E9%95%BF%E5%AD%99%E4%B8%B9%E5%87%A4/Desktop/webtest/1.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

在IE10的環境下進行測試的,沒問題。
解決辦法就是裝一個web伺服器,然後將檔案拷到專案中,以web伺服器中的路徑訪問,就沒有問題啦!形如http://localhost:8080/ajax/ajaxLoad.html

由於還有滑鼠懸浮事件,當我們將滑鼠懸浮在某個圖片上時,就會出現文字,移出時,圖片上的文字消失。

$(document).ready(function(){
        $('div .photo').hover(function(){
            $(this).find('.details').fadeTo('slow', 0.7);
        },function(){
                $(this).find('.details').fadeOut('slow');
        })
    });
或者可以將上面的程式碼組合起來減少冗餘程式碼:

$(document).ready(function(){
    $('div.photo').on('mouseenter mouseleave', 
            function(event){
            var $details = $(this).find('.details');
            if(event.type == 'mouseenter'){
                $details.fadeTo('slow', 0.7);
                //0.7代表的是透明度
            }
            else{
                $details.fadeOut('slow');
            }
        })
});

當我們使用上面的兩種程式碼為每個圖片新增滑鼠懸浮事件時,只有最初頁面上的那些圖片才會被繫結事件,而經過動態載入的圖片上卻沒能繫結上事件。因為事件處理程式只會新增到呼叫方法時已經存在的元素上,像通過這種動態追加的元素,不會繫結那些事件。
所以有兩種解決方案:
1. 在動態載入後重新繫結事件處理程式
2. 一開始就把事件繫結在存在的元素上,依賴於事件冒泡。

接下來就是使用jquery的委託方法;

$(document).ready(function(){
        $('#gallery').on('mouseenter mouseleave', 'div.photo', function(event){

            var $details = $(this).find('.details');
            if(event.type == 'mouseenter'){
                $details.fadeTo('slow', 0.7);
            }
            else{
                $details.fadeOut('slow');
            }
        })
    })

$(‘#gallery’).on(‘mouseenter mouseleave’, ‘div.photo’, function(event)中,在將’div.photo’作為第二個引數的情況下,.on()方法會把 this對映到 gallery中與該選擇符匹配的元素。換句話說,就是this指向gallery中的 div class= ‘photo’的元素。

所以在最後追加的頁面中,由於都屬於gallery 下的元素,所以每一個圖片都會加上相應的事件。
或許在你不知道要新增的頁面屬於哪個父級元素的話,可以將$(‘#gallery’).on( )中的’#gallery’替換成document。這樣就不必擔心選錯容器。因為document是頁面中所有元素的祖先。
但使用document有弊端:
當DOM巢狀結構很深,事件冒泡通過大量的祖先元素會有較大的效能損失。
但是還會有其他的原因讓我們選擇document作為委託作用域。
一般來說,只有當相應的DOM元素載入完畢,才會給它繫結事件處理程式。這就是為什麼我們要把程式碼放到$(document).ready(function(){}內部的原因。可是document元素是隨著頁面載入幾乎就立即可以呼叫的。把處理程式繫結到document不用等到完整的DOM構建結束。如上面的程式碼可以寫為:‘

(function($){
        $(document).on('mouseenter mouseleave', 'div.photo', function(event){

            var $details = $(this).find('.details');
            if(event.type == 'mouseenter'){
                $details.fadeTo('slow', 0.7);
            }
            else{
                $details.fadeOut('slow');
            }
        })
    })(jQuery);

因為沒有等到整個文件就緒,所以可以確保所有<div class= 'photo'>元素只要呈現在頁面上,就可以應用mouseenter 和mouseleave行為。

上面就是關於利用jQuery動態追加頁面資料以及事件委託的全部知識。下面附上原始碼;

<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
    <title>動態載入</title>
    <script type="text/javascript" src = "http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
    <style type="text/css">
    *{
        margin: 0px;
        padding: 0px;
    }


    #container{
        position: relative;
        width: 1300px;
        margin: 0 auto;
        /*background-color: #ccc;
        height: auto;*/
    }
    #gallery{
        position: relative;
        width: 1300px;
        margin: 0 auto;

    }
    .details{
        display: none;
    }

    .photo{
        padding: 20px;
        border-radius: 5px;
        border:1px solid #ccc;
        box-shadow: 0 0 5px #ccc;
        float: left;
        margin: 8px;
    }

    .photo img{

        /*z-index: 1;*/
        width: 200px;
        height: 300px;
        clear: both;
    }

    .photo .details{
        position: absolute;
        z-index: 2;
        padding-left: 20px;
        margin-top:-200px;
        /*clear: both;*/
        overflow: hidden;
    }
    .description{
        overflow: hidden;
        width: 200px;
        color: lightgreen;
        font-size: 18px;
        font-weight: bold;
    }

    .date{
        font-size:16px;
        margin: 20px 0px;
        color: red; 
    }
    .photographer{
        font-size:14px;
        font-family: "Arial" ;
    }
    .link a{

        clear: both;
        text-decoration: none;
        padding-left: 90%;


    }
    h1{
        text-align: center; 
    }
    </style>

    <script>
    $(document).ready(function(){

        var pageNum = 1;
        $("#more-photos").click(function(event){
            event.preventDefault();
            var $link = $(this);
            var url = $link.attr('href');
            console.log(url);
            if(url){
                $.get(url, function(data){
                    $("#gallery").append(data);
                });

                pageNum ++;
                if(pageNum < 4){
                    $link.attr('href', './'+pageNum+'.html');
                }


            else{
                $link.remove();
            }
            }
        })
    })

    // $(document).ready(function(){
    //  $('div .photo').hover(function(){
    //      $(this).find('.details').fadeTo('slow', 0.7);
    //  },function(){
    //          $(this).find('.details').fadeOut('slow');
    //  })
    // })

    $(document).ready(function(){
        $('#gallery').on('mouseenter mouseleave', 'div.photo', function(event){

            var $details = $(this).find('.details');
            if(event.type == 'mouseenter'){
                $details.fadeTo('slow', 0.7);
            }
            else{
                $details.fadeOut('slow');
            }
        })
    })

    </script>
</head>
<body>
<div id = "container">
<h1> Photo Gallery</h1>

<div id = "gallery">
    <div class = "photo">
        <img src = "./images/1.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye ....</div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

    <div class = "photo">
        <img src = "./images/2.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye.... </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/3.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye.... </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/4.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye .....</div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/5.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye ....</div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/6.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye ...</div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/7.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye.... </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/8.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye..... </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/9.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye ...... </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/10.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/11.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/12.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>


        <div class = "photo">
        <img src = "./images/13.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/14.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

        <div class = "photo">
        <img src = "./images/15.jpg">
        <div class = "details">
            <div class = "description">The Cullin Mountains, Isle of skye </div>
            <div class = "date">12/24/2000</div>
            <div class = "photographer"> Alasdair Dougall</div>
        </div>
    </div>

</div>

 <div class = "link"><a id = "more-photos" href = "1.html"> More Photos &gt;&gt;</a></div> 
</div>
</body>
</html>