【发布时间】:2023-04-03 05:42:01
【问题描述】:
我可能正在做一些非常愚蠢的事情,我知道这已经被问了上千种不同的方法。我想将信息、标题和描述放入我的 HTML 中。它只是在每个 div 中重复相同的信息,而不是填充其他节点。我的 JSON 对象、$.each 循环和 HTML 在下面。谢谢
var data = {
"available": true,
"screens": [{
"id": "s01",
"type": "Selector",
"config": {
"views": [{
"id": "sintel",
"type": "selectorItem",
"thumbnail": "http://test-cdn.selectablemedia.com/test/a/sintel/assets/img/thumb_sintel.png",
"title": "Sintel",
"description": "Small video. HTML5, native controls, start poster. Bottom, right social. Video + grid",
"info": "00:51"
}, {
"id": "bbb",
"type": "selectorItem",
"thumbnail": "http://test-cdn.selectablemedia.com/test/a/bbb/assets/img/thumb_bbb.png",
"title": "Big Buck Bunny",
"description": "Large video. HTML5, custom controls, social hover. Video + replay",
"info": "00:33"
}, {
"id": "walle",
"type": "selectorItem",
"thumbnail": "http://test-cdn.selectablemedia.com/test/a/walle/assets/img/thumb_walle.png",
"title": "WALL-E",
"description": "Small video. Youtube, custom controls. Left social. Video + carousel.",
"info": "02:30"
}]
}
}
]
}
$.each(data.screens, function(index, element) {
$(".container").find('.card-info').text(element.config.views[0].info);
$(".container").find('.card-title').text(element.config.views[0].title);
$(".container").find('.card-description').text(element.config.views[0].description);
});
<!--This is the HTML-->
<div class="container">
<div class="row">
<div class="col-md-6 ">
<div class="card">
<div class="card-image">
<div class="embed-responsive embed-responsive-16by9"
</div>
</div><!-- card image -->
<div class="card-content">
<span class="card-info"> </span>
<span class="card-title"> </span>
<span class="card-description"> </span>
</div><!-- card content -->
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 ">
<div class="card">
<div class="card-image">
<div class="embed-responsive embed-responsive-16by9">
</div>
</div><!-- card image -->
<div class="card-content">
<span class="card-info"> </span>
<span class="card-title"> </span>
<span class="card-description"> </span>
</div><!-- card content -->
</div>
</div>
</div>
</div>
【问题讨论】:
-
我认为你想要做的是
data.screens.forEach(screen => ... )构造行和screen.config.view.forEach(view => ...)构造每一行的单元格。您缺少的是您需要根据这些循环动态修改 HTML。通常在 HTML 中,这将采用<TABLE>、<TR>和<TD>的形式。您可能希望查看 jQuery 的 append 方法以了解如何做到这一点。 api.jquery.com/append。 HTH。 -
谢谢,我知道
append,但我想我对它为什么插入相同的内容感到困惑。你能举一个反对我的例子吗? -
我会用一些代码添加答案。