zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Prefilter JSON #310

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

如果我们不想展示每个从JSON获得小猫图片,我们可以进行在loop之前预筛选。

方法

让我过滤掉id:01

json = json.filter(function(val) {
  return (val.id !== 1);
});

代码


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

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

        var html = "";

        // Only change code below this line.
        json=json.filter(function(val){
          return (val.id!==1);
        })

        // Only change code above this line.

        json.forEach(function(val) {

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

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

          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

来源

https://www.freecodecamp.org/challenges/prefilter-json