zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Render Images from Data Sources #309

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

上两个挑战可以看到我们的JSON里有imageLink键,以及一个小猫的图片链接作为value

当我们用'loop这些对象时,可以使用imageLink属性在img`元素里展示这些图片。

方法

html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";

代码


<script>
  $(document).ready(function() {

    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {

        var html = "";

        json.forEach(function(val) {

          html += "<div class = 'cat'>";

          // Only change code below this line.

          html +="<img src=`" +val.imageLink +"` "+ "alt=`" + val.altText + "` >";

          // Only change code above this line.

          html += "</div>";

        });

        $(".message").html(html);

      });
    });
  });
</script>

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
    </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>

结果显示

image

点击按钮后,结果如下 image

来源

https://www.freecodecamp.org/challenges/render-images-from-data-sources