【问题标题】:Creating an object from html elements using JavaScript and jQuery使用 JavaScript 和 jQuery 从 html 元素创建对象
【发布时间】:2014-12-11 12:02:50
【问题描述】:

我想使用 JavaScript 和 jQuery 从 html 元素创建一个对象。

我要创建的对象是

{
  array:[{infraStructureType: 'value', hostId: 'value'}, {infraStructureType: 'value', hostId: 'value'}]
}

所以我创建上述对象的代码是

  var obj = {}, dataObj = {compareESX: []};
  $('.checkBox:checked').each(function () {
    obj.infraStructureType = $(event.target).attr('hostId');
    obj.hostId = $(event.target).attr('infrastructureType');
    console.log(obj);
    dataObj.compareESX.push(obj);
    console.log(dataObj);
  });

在上面的代码中,“console.log(obj)”给出了正确的输出,但是当我将它推入数组“dataObj.compareESX”时 只有最后一个'obj'的信息被推送每个循环执行的次数。

【问题讨论】:

  • 你从哪里得到event.target?您遍历每个检查的输入,但在每次迭代中从同一个对象获取属性。我认为你应该改用$(this).attr(...)

标签: javascript jquery html


【解决方案1】:

JS 使用引用方法调用。所以当更新 obj 时,它会更改所有值。你需要做深拷贝。使用这个

dataObj.compareESX.push(JSON.parse(JSON.stringify(obj)));

【讨论】:

【解决方案2】:

试试这个:FIDDLE 我们需要重新定义obj来清除之前的值。

var dataObj = {compareESX: []};
  $('.checkBox:checked').each(function (e) {
    var obj = {};
    obj.infraStructureType = $(this).attr('hostId');
    obj.hostId = $(this).attr('infrastructureType');
    //console.log(obj);
    dataObj.compareESX.push(obj);
    //console.log(dataObj);
  });
console.log(dataObj);

【讨论】:

    【解决方案3】:

    你必须把你的对象定义 var obj = {} inside 你的 each 循环。现在,您正在为循环中的每个条目使用 same 对象。相反,您应该为循环的每个复选框创建一个新对象。

    var dataObj = {compareESX: []};
    $('.checkBox:checked').each(function () {
      var obj = {};
      obj.infraStructureType = $(event.target).attr('hostId');
      obj.hostId = $(event.target).attr('infrastructureType');
      console.log(obj);
      dataObj.compareESX.push(obj);
      console.log(dataObj);
    });
    

    【讨论】:

    • 你会得到三个不同的dataObj。这不是提问者的预期输出。
    • 如果这样做,我的对象 'obj' 将在每次循环迭代时为空。我只希望我的对象在循环之外
    • @Pankaj 我想你只需要 dataObj 在循环之外。它包含一个数组compareESX,每个复选框都有obj 实例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多