//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
Run Code Online (Sandbox Code Playgroud)
您只想在每次迭代时克隆元素.一个DOM对象不是一个普通的JS对象(嗯,但它有更多的东西,这就是为什么你必须createElement在原始JS中使用来创建一个新对象):
$(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
});
});
Run Code Online (Sandbox Code Playgroud)
为什么你的代码失败,虽然你在每次迭代中"扩展"一个空对象,但它仍然总是指向同一个 DOM节点.你不断改变它的价值,然后追加它#target.此外,append工作方式实际上移动了对象,因此您没有获得重复的对象.