我有一些动态创建的div,每个div都包含一个标题。单击div会打开一个模式(单击时为空),标题也会第二次出现在模式中。我试图将类别描述附加到modals中,但只附加了最后一个JS obj的元素。例如,通过单击标题为"Animals“的div,模式弹出,我应该会看到"Animals are...”的描述。单击不同的div应该加载具有不同描述的模式。
我可以看到控制台中的所有元素,所以我不确定为什么会遇到这个问题-我认为$.each中缺少了一些东西,但我不确定是什么。
JS代码片段:
// 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);
})HTML代码片段:
<div class="modal-body">
<div class="category-desc" id="category-desc"></div>
</div>JS obj示例:
{
"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
}
]
}
}发布于 2019-05-06 22:19:16
原因是因为您在追加新值之前清空了#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);
})https://stackoverflow.com/questions/56006947
复制相似问题