【发布时间】:2015-08-12 06:20:36
【问题描述】:
我使用 typeahead.js 从 json 响应中的颜色项创建 li 元素
json:
"results": [
{
"title": "The Collection",
"attribute": "The Collection",
"url": "#/test",
"image": "images/products/londonretro-caine.jpg",
"color": ["brown", "yellow", "grey"]
},
json 有一个颜色键,有时是一个字符串,有时是一个包含多种颜色的数组
我已经遍历响应并动态创建了一个 html
html += '<li></li>'
我添加了一个条件来检查 json 中的项目是否是一个颜色数组。 如果它是一个颜色数组,我已经用尽可能多的 li 项目替换了 html,因为数组中有颜色
我尝试了两种方法:
1.一个是我使html等于新的li元素,如下所示:html += '<li></li>...'
- 另一个是我已将 html 更改为数组,并将 li 元素推入其中,替换了原始 html:
html.push('<li></li>')
使用方法1,我得到以下结果:
我把所有的颜色都放在一个单独的 li 中, 但我也得到了一个额外的第一个 li,颜色如下:
<li class='product-spot__variants-variant' style='background-color:brown,yellow,grey' title='brown,yellow,grey'>'brown,yellow,grey'</li>
使用方法2,我只得到最后一个颜色的最后一个li:
<li class='product-spot__variants-variant' style='background-color:grey' title='grey'>'grey'</li>
我在下面的代码中留下了这两种解决方案。 有任何想法吗?谢谢,如果不清楚请询问..
我的预输入代码:
suggestion: function (item) {
var glassesColor = item.color;
var html = "<li class='product-spot__variants-variant' style='background-color:"+ glassesColor +"' title='"+ glassesColor +"'>'"+ glassesColor +"'</li>";
_.forEach(item.color, function (k) {
if (typeof item.color === 'object') {
html += "<li class='product-spot__variants-variant' style='background-color:"+ k +"' title='"+ k +"'>'"+ k +"'</li>";
html = [];
html.push("<li class='product-spot__variants-variant' style='background-color:" + k + "' title='" + k + "'>'" + k + "'</li>");
var myhtml = html.join('');
html = myhtml;
}
});
//console.log(html);
var output = '<div class="search-autocomplete search-glasses">\n';
output += '<a href="' + item.url + '">';
output += (item.image ? '<img class="search-autocomplete__image" src="' + item.image + '" alt="' + item.title + '">' : '');
output += '<span class="search-autocomplete__title">' + item.title + '</span>';
output += (item.attribute ? '<span class="search-glasses__attribute">' + item.attribute + '</span>' : '');
output += '<ul class="product-spot__variants">';
output += html;
output += '</ul>';
output += '</a>\n';
output += '</div>\n';
return output;
}
【问题讨论】:
标签: javascript json typeahead.js