Dav*_*ion 1 html javascript ajax jquery loops
html
<div class="container">
<div class="card bg-warning">
<!-- put item.userId & item.id below this -->
<div class="card-header"></div>
<div class="card-body">
<!-- put item.title below this -->
<h5 class="card-title"></h5>
<!-- put item.body below this -->
<p class="card-text"></p>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
js
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $head = $(".card-header").html("user id: " + userId + " - " + "id: " + typeId);
var $title = $(".card-title").html(titleId);
var $text = $(".card-text").html(bodyId);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用.clone()克隆容器内的 div,然后使用它可以在克隆的 html中添加值并将其附加到容器中。
演示代码:
$(function() {
//hide first div or remove after append using `$(".card:first").remove()`
$(".card:first").hide()
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
$.each(result, function(index, item) {
var cards = $(".card:first").clone() //clone first divs
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
//add values inside divs
$(cards).find(".card-header").html("user id: " + userId + " - " + "id: " + typeId);
$(cards).find(".card-title").html(titleId);
$(cards).find(".card-text").html(bodyId);
$(cards).show() //show cards
$(cards).appendTo($(".container")) //append to container
});
}
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<div class="container">
<div class="card bg-warning">
<!-- put item.userId & item.id below this -->
<div class="card-header"></div>
<div class="card-body">
<!-- put item.title below this -->
<h5 class="card-title"></h5>
<!-- put item.body below this -->
<p class="card-text"></p>
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5712 次 |
| 最近记录: |