为什么我每页只有 1 个 gif 而不是多个 gif?

Why do I have only 1 gif per page instead of multiple gifs?

我是 jQuery 的新手,我想弄清楚如何在输入关键字并单击 'submit' 后让多个 gif 显示在页面上。在我的 api 键中,我认为设置数字 'limit=10'(例如 10)假设每页有 10 个 gif 图像?

$('#searchgifs').on('click', function() {
    var input = $('#search').val();
    $.get('https://api.giphy.com/v1/gifs/search?q=' + input + '&api_key=apikey&limit=10', function(response) {
      $('#img').html("<img src=" + response.data[0].images.downsized_large.url + ">")
    })
  });
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    
</head>
<body>
<input id="search" class="form-control mr-sm-2" type="text" placeholder="Search" value="">
<button class="btn btn-outline-success my-2 my-sm-0" id="searchgifs" type="submit">Search</button>
<div id="img">
    
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>   
<script src="scripts/script1.js"></script>
</body>
</html>

您似乎有两个问题:第一个是您只将其中一个结果设置为元素,第二个是您将元素的内容设置为第一个结果的内容,而不是附加它。下面的代码片段应该有效。

我做的两个改动:

  1. 使用 $.each() 函数对所有结果进行处理,而不是使用数组键仅对 1 个进行处理
  2. 使用.appendTo()函数向某个元素添加内容,而不是设置内容。第一个ADDS内容,后面覆盖当前值

$('#searchgifs').on('click', function() {
    var input = $('#search').val();
    $.get('https://api.giphy.com/v1/gifs/search?q=' + input + '&api_key=apikey&limit=10', function(response) {
      $.each(response.data, function(index, gif){
      $("<img src=" + gif.images.downsized_large.url + ">").appendTo(('#img'))
      });
      
    })
  });
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    
</head>
<body>
<input id="search" class="form-control mr-sm-2" type="text" placeholder="Search" value="">
<button class="btn btn-outline-success my-2 my-sm-0" id="searchgifs" type="submit">Search</button>
<div id="img">
    
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>   
<script src="scripts/script1.js"></script>
</body>
</html>