修改克隆元素并重新插入dom-jquery

时间:2010-03-16 05:34:48

标签: jquery

    //dom    

    <div id='toBeCloned'><span>Some name</span></div>
    <div id='targetElm'></div>

    //js
        $(function () {
            //creating a clone
            var _clone = $('#toBeCloned').clone(true);
    // target element
            var _target = $('#targetElm');

    //now target element is to be filled with cloned element with data of span changed
            var _someData = [1, 2, 3, 4];

    //loop through data
            $.each(_someData, function (i, data) {
                var _newElm = {};
                $.extend(_newElm, _clone);//copy cloned to  new Elm
                _newElm.find('span').html(data); //edit content of span
                alert('p'); // alert added to show that append in next line inspite of adding new element to dom just updating the previous one
                _target.append(_newElm);//update target
            });
        });


expected Result:
1 2 3 4
resut iam getting is
4

1 个答案:

答案 0 :(得分:6)

您只想在每次迭代时克隆元素。一个DOM对象不是一个普通的JS对象(嗯,但是它有更多的东西,这就是为什么你必须在原始JS中使用createElement来创建一个新对象):

$(function () {
    // element to be cloned
    var _clone_me = $('#toBeCloned');
    // target element
    var _target = $('#targetElm');

    //now target element is to be filled with cloned element with data of span changed
    var _someData = [1, 2, 3, 4];

    //loop through data
    $.each(_someData, function (i, data) {
        var _newElm = _clone_me.clone(true); // clone copy
        _newElm.find('span').html(data);  //edit content of span
        _target.append(_newElm); //update target
    });
});

为什么你的代码失败了,虽然你在每次迭代中“扩展”一个空对象,但它仍然总是引用相同的 DOM节点。您不断更改其值,并将其附加到#target。此外,append的工作方式实际上会移动对象,因此您没有获得重复的对象。