提问者:小点点

如何循环HTML元素并填充JSON-Object?


我正在遍历html文件中的所有html标记,检查这些标记是否匹配条件,并尝试组成以下模式的JSON-object:

[
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  },
{    title: 'abc',    date: '10.10.10',    body: ' P tags here',    href: ''  }
]

但是我只想为“header”类的元素创建新条目,所有其他元素都必须添加到先前创建的条目中。 我怎么才能做到呢?

当前代码:

$('*').each((index, element) => {


  if ( $(element).hasClass( "header" ) ) {
      jsonObject.push({
          title: $(element).text()
      });
  };
  if( $(element).hasClass( "date" )) {
      jsonObject.push({
          date: $(element).text()
      });
   }

   //links.push($(element))
});
console.log(jsonObject)

结果是:

  {
    title: 'TestA'
  },
  { date: '10.10.10' },
  {
    title: 'TestB'
  },
  { date: '10.10.11' }

在这个阶段,我希望它是这样的:

      {
        title: 'TestA'
      ,
       date: '10.10.10' },
      {
        title: 'TestB'
      ,
       date: '10.10.11' }

谢谢你抽出时间!


共1个答案

匿名用户

$('*').each((index, element) => {
  var obj = {};

  if ( $(element).hasClass( "header" ) ) {
    obj.title = $(element).text();
  };
  if( $(element).hasClass( "date" )) {
    obj.date = $(element).text()
   }

    jsonObject.push(obj);

});

相关问题