簡體   English   中英

在DOM元素上每個Jquery - 推入數組錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM