[英]Jquery each on DOM element - Push in array error
我尝试在我的DOM上使用each()函数来动态添加字段。 但是这个代码我遇到了一个问题:
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);
push函数总是推送最后一个子节点,而不是另一个节点,但在我的控制台登录中具有良好的值。
log 1:{name:“a”,values:Array(1)}
log 2:{name:“b”,values:Array(1)}
记录3:[
{name:“b”,values:Array(1)}
{name:“b”,values:Array(1)}
]
为什么?
为什么?
因为在每次迭代中你都会覆盖同一个对象nouvelle_entree
。
您需要在每次迭代中定义对象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);
通过在函数外声明对象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(",");
console.log(nouvelle_entree);
mockSystem.input.push(nouvelle_entree);
});
console.log(mockSystem.input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.