Jquery淺複製與深複製

來源:互聯網
上載者:User

標籤:this   console   結構   指定   代碼   top   click   使用   需要   

 

複製節點是DOM的常見操作,jQuery提供一個clone方法,專門用於處理dom的複製

.clone()方法深度 複製所有匹配的元素集合,包括所有匹配元素、匹配元素的下級元素、文位元組點。

clone方法比較簡單就是複製節點,但是需要注意,如果節點有事件或者資料之類的其他處理,我們需要通過clone(ture)傳遞一個布爾值ture用來指定,這樣不僅僅只是複製單純的節點結構,還要把附帶的事件與資料給一併複製了

例如:

HTML部分<div></div>JavaScript部分$("div").on(‘click‘, function() {//執行操作})//clone處理一$("div").clone()   //只複製了結構,事件丟失//clone處理二$("div").clone(true) //結構、事件與資料都複製

使用上就是這樣簡單,使用複製的我們需要額外知道的細節:

  • clone()方法時,在將它插入到文檔之前,我們可以修改複製後的元素或者元素內容,如右邊代碼我 $(this).clone().css(‘color‘,‘red‘) 增加了一個顏色
  • 通過傳遞true,將所有綁定在原始元素上的事件處理函數複製到複製元素上
  • clone()方法是jQuery擴充的,只能處理通過jQuery綁定的事件與資料
  • 元素資料(data)內對象和數組不會被複製,將繼續被複製元素和原始元素共用。深複製的所有資料,需要手動複製每一個
<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>    <style>    .left,    .right {        width: 300px;        height: 120px;    }        .left div,    .right div {        width: 100px;        height: 90px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;        background: #bbffaa;    }    </style></head><body>    <h2>通過clone複製元素</h2>    <div class="left">        <div class="aaron1">點擊,clone淺拷貝</div>        <div class="aaron2">點擊,clone深拷貝,可以繼續觸發建立</div>    </div>    <script type="text/javascript">        //只複製節點        //不複製事件        $(".aaron1").on(‘click‘, function() {            $(".left").append( $(this).clone().css(‘color‘,‘red‘) )        })    </script>    <script type="text/javascript">        //複製節點        //複製事件        $(".aaron2").on(‘click‘, function() {            console.log(1)            $(".left").append( $(this).clone(true).css(‘color‘,‘blue‘) )        })    </script></body></html>

 

Jquery淺複製與深複製

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.