如何在不引用原始对象的情况下复制JavaScript对象?

时间:2017-03-21 12:00:31

标签: jquery

此处编辑后,行数据更改为新行。我只需要创建这个对象的副本。但它引用了原文。原件中发生的更改也反映在复制的对象中。

$(document).ready(function () {
    var nEditing = null;
    var rowdata = null;
    var tabIndex = null;
    var table = null;
    var row = null;

    $('table').on('click', 'a.edit', function (e) {
        e.preventDefault();

        /* Get the row as a parent of the link that was clicked on */
        var nRow = $(this).parents('tr')[0];
        var table = $(this).parents('table')[0];
         row = $(this).parents('tr').find('td');

        if (nEditing !== null && nEditing != nRow) {
            /* A different row is being edited - the edit should be cancelled and this row edited */
            restoreRow(table, rowdata, nEditing);
            editRow(row, nRow);
            nEditing = nRow;
            rowdata = row;
        }
        else 
         if (nEditing == nRow && this.innerHTML == '<i class="fa fa-save"></i>') {
            /* This row is being edited and should be saved */
            saveRow(row, nEditing);
            nEditing = null;
            rowdata = null;
        }
        else {
            /* No row currently being edited */
            nEditing = nRow;
            rowdata = row;
            editRow(row, nRow);

        }
    });


});
//Js edit row inline--------------------------------------------------------------------------------------------
function editRow(table, nRow) {
    //var rowData = table.row(nRow).data();



        // do something with productId, product, Quantity

    var td = $('>td', nRow);
    var Count = td.length-1;
    for (var i = 1; i < Count; i++)
    {
        td[i].innerHTML = '<input type="text" style="width:100%" value="' +table.eq(i).text() + '">';
    }



    td[Count].innerHTML = '<a class="edit" href="#"><i class="fa fa-save"></i></a>';
}




//save inline edit row----------------------------------------------------------------------------------------------
function saveRow(row, nRow) {
    var inputs = $('input', nRow);
    var rowData = row;

    var td = $('>td', nRow);
    var Count = td.length - 1;
    for (var i = 1; i < Count; i++) {
        rowData[i] = inputs[i-1].value;
        td[i].innerHTML = rowData[i];
    }



    td[Count].innerHTML = '<a class="edit" href="#"><i class="fa fa-edit"></i></a>';



}




//Restore the unsaved thing----------------------------------------------------------------------------------------
function restoreRow(table, rowdata, nEditing) {
    var td = $('>td', nEditing);
    var Count = td.length - 1;
    for (var i = 1; i < Count; i++) {
        td[i].innerHTML = '' + rowdata[i].innerHTML + '';
    }

    td[Count].innerHTML = '<a class="edit" href="#"><i class="fa fa-edit"></i></a>';


}

1 个答案:

答案 0 :(得分:0)

如果您要复制DOM元素,则需要cloneNode函数:https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

如果您要复制普通的javascript对象,那么根据this question,这可能是最快的:

JSON.parse(JSON.stringify(obj))

请仔细阅读链接的问题以获取更多信息。