使用文本和span标记创建动态li标记

问题描述 投票:0回答:2

我有一个JSON数组如下:

var teamDetails=[ 
 { "pType" : "Search Engines", "count" : 5},
 { "pType" : "Content Server", "count" : 1},
 { "pType" : "Search Engines", "count" : 1},
 { "pType" : "Business", "count" : 1,},
 { "pType" : "Internet Services", "count" : 1},
];

我想在其中创建带有JSON数据的动态ul和li标签

我希望数据放置如下:

<ul class="list-unstyled">
<li>
    ***Here the json ptype value***
    <span class="pull-right">
        <strong>
            <h5>***here json count value***</h5>
        </strong>
    </span>
</li>
</ul>

如何为每个数据动态获取此输出..?

我尝试使用此代码,但无法弄清楚如何附加文本li和span标签?

var clist=$('ul.list-unstyled')

dataProjectCount.forEach(function(a){
  a.count=a.count+" Projects";
  console.log(a.count);

  var li=$('<li/>').appendTo(clist);
  var aa=$('<span/>').addClass('pull-right').appendTo(clist);
});
javascript jquery html json ajax
2个回答
2
投票

创建映射输入teamDetails数组项的li元素,然后将它们附加到ul容器中

const teamDetails=[ 
 { "pType" : "Search Engines", "count" : 5},
 { "pType" : "Content Server", "count" : 1},
 { "pType" : "Search Engines", "count" : 1},
 { "pType" : "Business", "count" : 1,},
 { "pType" : "Internet Services", "count" : 1},
];

const liElements = teamDetails.map(el => $(`<li>${el.pType}<span class="pull-right><strong><h5>${el.count}</h5></strong></span></li>`));
$('.list-unstyled').append(liElements);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list-unstyled">
</ul>

0
投票

Extracting from Array of Objects

  • 首先使用<ul class="list-unstyled"></ul>.html()添加到DOM。
  • 在外部阵列上使用.map()
  • 在数组中的每个对象上使用Object.values()
  • 在每个对象的值上使用.map()
  • 在交替迭代上使用HTML字符串的片段
  • 在将值插入每个片段后,结果是一个字符串数组
  • 使用.join()将字符串数组转换为单个字符串
  • .append()将字符串添加到空列表中

演示

var teamDetails = [{pType:"Search Engines",count:5},{pType: "Content Server",count: 1},{pType:"Business",count: 1},{pType: "Internet Services",count: 1}];

$('body').html(`<ul class="list-unstyled"></ul>`);

var result = teamDetails.map(function(item) {
  var obj = Object.values(item).map(function(val, idx) {
    if (idx % 2 === 0 || idx === 0) {
      var str = `<li><b class='tD A'>${val}  </b>`;
    } else {
      var str = `<b class='tD B'>${val}</b></li>`;
    }
    return str;
  });
  return obj;
});

var string = result.join(' ').replace(/,/g, '');

$('.list-unstyled').append(string);
.tD {
  display: inline-block;
  font: 16px/1.2 Verdana;
}

.A {
  width: 15ch
}

.B {
  font: 700 20px/1 Consolas;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.