How do I copy the data of an element with jQuery?

This question already has an answer here:

  • What is the most efficient way to deep clone an object in JavaScript? 57 answers

  • To really only copy the data-*, this is quite straightforward:

    $(destination).data( $(source).data() );
    

    This is because using .data() no arguments will return a key-value object of all pieces of data and vice versa you can also update multiple pieces data at once using a key-value object.


    UPDATE 25th May 2017

    A clever alternative in JavaScript without jQuery appears to be:

    Object.assign(destination.dataset, source.dataset);
    

    Answer to:

    a) Iterate over data items

    $.each(element.data(), function (name, value) {
        // ... do something
    })
    

    If element is a DOM element, use this:

    $.each($.data(element), function (name, value) {
        // ... do something
    })
    

    To give another alternative, ie instead of cloning the whole object you can copy the data object to a new array containing name/value pairs followingly:

    
    function getOriginalElementData(domElementJQueryObject){
        var originalElementData = new Array();
        $.each(domElementJQueryObject.data(),function(name,value) {
           originalElementData.push({"name":name,"value":value});
        });
    
        return originalElementData;
    }
    

    To restore the data to another object:

    
    function restoreOriginalElementData(domElementJQueryObject,originalElementData){
        for(var i=0;i<originalElementData.length;i++){
            domElementJQueryObject.data(originalElementData[i].name,originalElementData[i].value);
        }
    }
    

    The part to iterate through the data items is copied from this answer: jQuery loop through data() object

    链接地址: http://www.djcxy.com/p/6942.html

    上一篇: Javascript深拷贝对象

    下一篇: 如何使用jQuery复制元素的数据?