将每个新类型的孩子包装成一行

时间:2017-07-03 06:37:09

标签: javascript jquery

每个相同的子类型都应该包含div。问题是我得到包含所有孩子的单个数组。所以我在它上面运行循环并尝试创建新的div并在子类型改变时将其关闭但是写得不好。

fiddle

var items = [{
  "type": "child1",
  "name": "1 "
}, {
  "type": "child1",
  "name": "1 "
}, {
  "type": "child1",
  "name": "1 "
}, {
  "type": "child2",
  "name": "2 "
}, {
  "type": "child2",
  "name": "2"
}, {
  "type": "child3",
  "name": "3 "
}, {
  "type": "child3",
  "name": "3 "
}, {
  "type": "child3",
  "name": "3"
}]
var child = "";
var html = ''

items.forEach(function(item) {
  if (child !== item.type) {
    html += '<div>'
  }
  html += '<div>' + item.name + ' </div>';
  if (child !== item.type && child) {
    html += '</div>'
  }
  child = item.type;

})

document.getElementById('html').innerHTML = html;
div { border:1px solid black }
<div id="html"></div>

3 个答案:

答案 0 :(得分:1)

你应该做什么,当你检查孩子是否与item.type不一样时,你应该添加一个结束</div>和一个新的开放<div>

items.forEach(function(item) {
 if(child != item.type){
    html += '</div>';
    html += '<div>';
 }
 html += '<div>' + item.name + ' </div>';
 child = item.type;
})

演示:https://jsfiddle.net/0sz9xpxq/2/

答案 1 :(得分:1)

你可以试试这个, https://jsfiddle.net/trupti11/0sz9xpxq/4/

var html = '<div>';  
items.forEach(function(item) {
      if (child != item.type && child) {
        html += '</div><div>'+ item.name;
      }
      else
      {
      html += item.name;
      }
      child = item.type;

    })
    html += '</div>';

答案 2 :(得分:0)

而不是凌乱的文本操作,您可以使用document.createElement来做得更清洁。我们a great answer to this SO question讨论了使用createElement与将字符串添加到innerHTML的好处

var child = "";
var html = document.getElementById('html');
var node;

items.forEach(function(item) {
  if (child !== item.type) {
    if (node) {
        html.appendChild(node);
    }
    node = document.createElement('div');
  }
    var newElem = document.createElement('div');
    newElem.innerHTML = item.name;
    node.appendChild(newElem);

  child = item.type;

});

html.appendChild(node);

Fiddle