[英]Jquery each on DOM element - Push in array error
I try to use each() function on my DOM to get field dynamically added. 我尝试在我的DOM上使用each()函数来动态添加字段。 But I hava a probleme with this code :
但是这个代码我遇到了一个问题:
var nouvelle_entree=new Object();
$('div[name="declaration-ligne-entree"]').each(function () {
nouvelle_entree.name=$(this).children('input[name="system-input-name"]').val();
nouvelle_entree.values=$(this).children('input[name="system-input-valeur"]').val().split(",");
console.log(nouvelle_entree);
mockSystem.input.push(nouvelle_entree);
});
console.log(mockSystem.input);
The push function always push the last child and not the other but on my console log in have the good values. push函数总是推送最后一个子节点,而不是另一个节点,但在我的控制台登录中具有良好的值。
log 1 : {name: "a", values: Array(1)}
log 1:{name:“a”,values:Array(1)}
log 2 : {name: "b", values: Array(1)}
log 2:{name:“b”,values:Array(1)}
log 3: [
记录3:[
{name: "b", values: Array(1)}
{name:“b”,values:Array(1)}
{name: "b", values: Array(1)}
{name:“b”,values:Array(1)}
]
]
Why ? 为什么?
Why ?
为什么?
Since in every iteration you're overwriting the same object nouvelle_entree
. 因为在每次迭代中你都会覆盖同一个对象
nouvelle_entree
。
You need to define the object nouvelle_entree
in every iteration not just the first time, else the variable will always contains the informations of the last iteration, eg : 您需要在每次迭代中定义对象
nouvelle_entree
而不仅仅是第一次,否则变量将始终包含最后一次迭代的信息,例如:
$('div[name="declaration-ligne-entree"]').each(function() {
var nouvelle_entree = {};
nouvelle_entree.name = $(this).children('input[name="system-input-name"]').val();
nouvelle_entree.values = $(this).children('input[name="system-input-valeur"]').val().split(",");
mockSystem.input.push(nouvelle_entree);
});
console.log(mockSystem.input);
By declaring the object nouvelle_entree
outside the function you are overwriting the same object again and again which results only the last object to be pushed into the array. 通过在函数外声明对象
nouvelle_entree
,您将一次又一次地覆盖同一对象,这会导致最后一个对象被推入到数组中。
Create the object in each of the iteration. 在每次迭代中创建对象。
$('div[name="declaration-ligne-entree"]').each(function () {
var nouvelle_entree = {};
nouvelle_entree.name=$(this).children('input[name="system-input-name"]').val();
nouvelle_entree.values=$(this).children('input[name="system-input-valeur"]').val().split(",");
console.log(nouvelle_entree);
mockSystem.input.push(nouvelle_entree);
});
console.log(mockSystem.input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.