【问题标题】:use loop through data json value and display each of it into card使用循环遍历数据 json 值并将每个值显示到卡片中
【发布时间】:2021-05-04 14:17:01
【问题描述】:

我在使用循环时遇到问题,因为我不知道在这种情况下使用哪种循环(对不起,我还在学习 jquery 和 js!)。在结果页面中,我创建了卡片以将每个数据与 json 分开,但我一直坚持如何在每张卡片中显示数据。以下是细分:

结果示例

代码

<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

<title>Display data json into cards</title>
</head>

<body>
<div class="container">
    <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">

        <div class="card-header"></div>

        <div class="card-body">

            <h5 class="card-title"></h5>

            <p class="card-text"></p>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"</script>
<script>
    $(function () {
        $.ajax({
            url: "https://jsonplaceholder.typicode.com/posts",
            success: function (result) {

                $.each(result, function (index, item) {
                    var userId = item.userId; //this should be in div class = "card-header"
                    var typeId = item.id; //this should be in div class = "card-header"
                    var titleId = item.title; //this should be in h5 class = "card-title"
                    var bodyId = item.body; //this should be in p class = "card-text"

                    var html = '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                        html += '<div class="card-header"></div>';
                        html += '<div class="card-body">';
                        html += '<h5 class="card-title"></h5>';
                        html += '<p class="card-text"></p>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';

                    //use loop below here and inject to div.container    

                    $(".container").html(html); //using .html() will display one card,use loop to display each card

                });
                // console.log('success', result);
                // console.log(result[0].body);
                // console.log($(result).length);
            }
        });
    });
</script>
</body>

</html>

抱歉问的有点多,谢谢你的帮助!

【问题讨论】:

  • html += '&lt;p class="card-text"&gt;'+ bodyId +'&lt;/p&gt;'; 和其他人的想法一样......这是你想要的吗??
  • 是的,可以这样做,但是 div.container 下面的第一个 div 仍然显示空数据,而从 var html 创建的 div 被添加。所以我的想法是,它应该使用循环来解决它
  • 所以这意味着不需要它??将其删除,以便在 ajax 之前添加 $('.container &gt; div').remove();
  • 您也可以使用 css .container &gt; div:eq(0){ display : none; } 隐藏第一个 div .. 您仍然可以同时删除 css 和 js
  • 好的,我试过了,先生,它有效!但是,如果您不介意,我还有更多问题。所以我编辑了代码,因此注入从 $(".container").append(html) 更改为 $(".container").html(html ) 并且它只显示一张卡片。为了解决我需要使用循环的问题吗?如果是这样,您能解释一下循环它的方法吗?感谢先生的帮助!

标签: javascript jquery ajax loops for-loop


【解决方案1】:
  • 您已经使用 .each 进行了循环,问题是您没有传递/连接 js/html 中的变量
  • 关于但是 div.container 下面的第一个 div 仍然显示空数据,而从 var html 创建的 div 被添加您可以使用 css 或/和 js 来隐藏/删除它

[1] 使用 css,js .append()

$(function () {
    $('.container > div').remove();
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts",
        success: function (result) {
            $.each(result, function (index, item) {
                var userId = item.userId; //this should be in div class = "card-header"
                var typeId = item.id; //this should be in div class = "card-header"
                var titleId = item.title; //this should be in h5 class = "card-title"
                var bodyId = item.body; //this should be in p class = "card-text"

                var html = '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                    html += '<div class="card-header">user: ' + userId +' typeId: '+ typeId +'</div>';
                    html += '<div class="card-body">';
                    html += '<h5 class="card-title">'+ titleId +'</h5>';
                    html += '<p class="card-text">'+ bodyId +'</p>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';

                //use loop below here and inject to div.container    

                $(".container").append(html);

            });
            // console.log('success', result);
            // console.log(result[0].body);
            // console.log($(result).length);
        }
    });
});
.card:nth-child(1){
  display : none;
}
.card{
  margin : 20px;
  padding : 20px;
  background : #eee;
  border : 1px solid #333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">

        <div class="card-header"></div>

        <div class="card-body">

            <h5 class="card-title"></h5>

            <p class="card-text"></p>
        </div>
    </div>
</div>

[2]如果你想使用.html()你需要在each()之前定义var html然后让.each更新html +=值然后使用@ .each()之后的987654331@ 我还是更喜欢第一种解决方案

$(function () {
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts",
        success: function (result) {
            var html = '';
            $.each(result, function (index, item) {
                var userId = item.userId; //this should be in div class = "card-header"
                var typeId = item.id; //this should be in div class = "card-header"
                var titleId = item.title; //this should be in h5 class = "card-title"
                var bodyId = item.body; //this should be in p class = "card-text"

                html += '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                    html += '<div class="card-header">user: ' + userId +' typeId: '+ typeId +'</div>';
                    html += '<div class="card-body">';
                    html += '<h5 class="card-title">'+ titleId +'</h5>';
                    html += '<p class="card-text">'+ bodyId +'</p>';
                    html += '</div>';
                    html += '</div>';
                    html += '</div>';

                //use loop below here and inject to div.container    

                
            });
            $(".container").html(html);

            // console.log('success', result);
            // console.log(result[0].body);
            // console.log($(result).length);
        }
    });
});
.card{
  margin : 20px;
  padding : 20px;
  background : #eee;
  border : 1px solid #333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
    <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">

        <div class="card-header"></div>

        <div class="card-body">

            <h5 class="card-title"></h5>

            <p class="card-text"></p>
        </div>
    </div>
</div>

【讨论】:

    【解决方案2】:

    尝试使用以下解决方案:

    要在字符串中绑定变量,请使用 ``

    $(function() {
      var html = "";
      $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts",
        success: function(result) {
          $.each(result, function(index, item) {
            html +=
              '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
            html += `<div class="card-header">userid: ${item.userId} - id: ${item.id}</div>`;
            html += '<div class="card-body">';
            html += `<h5 class="card-title">${item.title}</h5>`;
            html += `<p class="card-text">${item.body}</p>`;
            html += "</div>";
            html += "</div>";
            html += "</div>";
            //using .html() will display one card,use loop to display each card
          });
          $(".container").html(html);
        }
      });
    });
    

    并在 stackblitz 演示中查看以下内容:

    https://stackblitz.com/edit/js-xfs15o?file=index.html

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2016-09-26
      • 2018-01-06
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多