How to create html structure which will allow only 3 div elements in each li. In React + underscore.js

被刻印的时光 ゝ 提交于 2019-12-13 02:26:11

问题


For creating this structure i want to use only underscore.js methods. I have below array .

 var xyz = [{
    'name': 'test'
 },{
    'name': 'test1'
 },{        
    'name': 'test2'
 },{ 
    'name': 'test3'
 },{ 
    'name': 'test4'
 },{
    'name': 'test5'

}];

And HTML structure should create like this -

<ul>
    <li>
       <div><span>test3</span></div>
       <div><span>test4</span></div>
       <div><span>test5</span></div>
    </li>
    <li>
       <div><span>test6</span></div>
       <div><span>test7</span></div>
       <div><span>test8</span></div>
    </li>
</ul>  

I am using React and underscore.js on my project.


回答1:


An example of a pure React function (it could also be a component), you could do something like the following:

    <span>
        {_.map(_.chunk(xyz, 3), (innerItem, i) => (
            <ul key={i}>
                {_.map(innerItem, ({name}, j) => (<li key={j}>{name}</li>))}
            </ul>
        ))}
    </span>



回答2:


Try this:

$(document).ready(function(){
  var xyz = [{'name':'test'},{'name':'test1'},{'name':'test2'},{'name':'test3'},{'name':'test4'},{'name':'test5'}];

  var htmlStr = "<ul><li>";
  var cnt = 0;
  $(xyz).each(function(i,v) {
    if(cnt != 0 && cnt % 3 == 0) {
      htmlStr += "</li><li>";
    }
    htmlStr += "<div><span>"+v.name+"</span></div>";
    cnt++;
  });
  htmlStr += "</li></ul>";
  $("#test").html(htmlStr)
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="test"></div>



回答3:


You can split the array into chunks and use underscore _.template method for creating html:

var xyz = [{
'name': 'test'
},{
    'name': 'test1'
},{        
    'name': 'test2'
},{ 
    'name': 'test3'
},{ 
    'name': 'test4'
},{
    'name': 'test5'
}];

var chunkedXyz = _.chain(xyz).groupBy(function(element, index){
  return Math.floor(index/3);
}).toArray().value();

var liTemplate = _.template("<% _.each(liElements, function(liContent) { %> <div><span><%= liContent.name %></span></div> <% }); %>");
var ulTemplate = _.template("<% _.each(chunkedXyz, function(liItem) { %> <li><%= liTemplate({liElements: liItem}) %></li> <% }); %>");

var layout = "<ul>" + ulTemplate({
    chunkedXyz: chunkedXyz,
    liTemplate: liTemplate
}) + "</ul>";

console.log(layout.toString());

https://jsfiddle.net/1m5ayhzw/



来源:https://stackoverflow.com/questions/38008023/how-to-create-html-structure-which-will-allow-only-3-div-elements-in-each-li-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!