我有一些动态创建的div,每个div都包含一个Title。单击div会打开一个模态(单击后会清空),标题也会再次出现在模态中。我试图将类别描述附加到模态中,但仅附加最后一个JS obj的元素。例如,通过单击标题为“ Animals”的div,将弹出模式,我应该看到描述“ Animals are ...”。点击不同的div会加载带有不同说明的模式。
我可以在控制台中看到所有元素,所以我不确定为什么会遇到这个问题---我相信$.each
中缺少某些内容,但是我不确定是什么。
// axios code here
loadCategories(){
let categs = _categories
// down below I'm duplicating the template to create one div for each category
let $host = $("#host");
for (var i = 0; i < categs.length; i++) {
let $template = $("#template").clone();
$("#cat-title").empty();
$("#cat-title").append(categs[i].Title);
$("#cat-box-id").attr("data-category", categs[i].Title);
$host.append($template.html());
console.log('catdesc ' + categs[i].Description) // does show everything
}
$.each(categs, function(i, val) {
$("#category-desc").empty();
$("#category-desc").append(val.Description);
})
<div class="modal-body">
<div class="category-desc" id="category-desc"></div>
</div>
{
"d": {
"results": [
{
"Title": "Animals",
"Description": "Animals are multicellular eukaryotic organisms that form the biological kingdom Animalia. With few exceptions, animals consume organic material, breathe oxygen, are able to move, can reproduce sexually, and grow from a hollow sphere of cells, the blastula, during embryonic development. Over 1.5 million living animal species have been described\u2014of which around 1 million are insects\u2014but it has been estimated there are over 7 million animal species in total.",
"SortOrder": null
},
{
"Title": "Colors",
"Description": "Color (American English), or colour (Commonwealth English), is the characteristic of human visual perception described through color categories, with names such as red, orange, yellow, green, blue, or purple.",
"SortOrder": null
},
// other data
{
"Title": "World Capitals",
"Description": "A capital city (or simply capital) is the municipality exercising primary status in a country, state, province, or other administrative region, usually as its seat of government.",
"SortOrder": null
}
]
}
}
答案 0 :(得分:0)
原因是因为您在附加新值之前清空了#category-desc
,所以它仅附加了最后一个值。
$.each(categs, function(i, val) {
// $("#category-desc").empty();
// ^ ^ don't empty content if you want value to be append
$("#category-desc").append(val.Description);
})