我希望将每个<ul>
variable_name
我尝试在if语句中插入ul但它不起作用。是否可以将ul放在if语句之外?
我们说variable_name = [dog,dog,dog,cat,cat,mouse,mouse,mouse,mouse];
我想要的输出是:
<ul>
<li> dog </li>
<li> dog </li>
<li> dog </li>
</ul>
<ul>
<li> cat </li>
<li> cat </li>
</ul>
<ul>
<li> mouse </li>
<li> mouse </li>
<li> mouse </li>
<li> mouse </li>
Code:
<% for(var j=0;j<array4.length;j++) { %>
<% if(array4[j].input_type == "radio") { %>
<li class="list-group-item radio-choice" id="chk_<%=array4[j].variable_name%>" value=""><%=array4[j].answer_text%> </li>
<%} }%>
答案 0 :(得分:1)
在Node中你可以这样做(直接在模板中,例如eJS):
<%
var variable_name = ['dog','dog','dog','cat','cat','mouse','mouse','mouse','mouse'];
var uls = [];
variable_name.forEach(function(item) {
uls[item] = uls[item] ? ++uls[item] : 1;
});
for(var key in uls) {
%><ul><%
for (var i=0; i<uls[key]; i++) {
%><li><%= key %></li><%
}
%></ul><%
}
%>
您可以使用Javascript中的控制台日志对此进行测试,如下所示:
var variable_name = ['dog','dog','dog','cat','cat','mouse','mouse','mouse','mouse'];
var uls = [];
variable_name.forEach(function(item) {
uls[item] = uls[item] ? ++uls[item] : 1;
});
for(var key in uls) {
console.log('<ul>');
for (var i=0; i<uls[key]; i++) {
console.log('<li>'+key+'</li>');
}
console.log('</ul>');
}