下面的代码正在从Giphy中提取数据。我试图让用户搜索一个术语并在页面上显示图像。我目前只有一个图像显示,它正在创建按钮的cookie跟踪,允许用户返回并单击之前看到的图像。我需要遍历并显示从console.log(data)返回的每个图像url的一个图像。我可以获取数据以在控制台中显示图像URL但不为每个创建按钮。任何帮助表示赞赏。
<div class="wrapper">
<div class="container">
<div id="animalButtons"></div>
<form class="input-append">
<div id="field">
<input class="input" id="formValueId" type="text" placeholder="Type something"/>
<input type="button" class="myButton" value="Search" />
</div>
</form>
<div id="field1"></div>
<div id="searchResults"></div>
</div>
</div>
function buttonFeature(value){
request.open('GET', 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q='+value, true);
request.send('GET', 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q='+value, true);
};
document.addEventListener('DOMContentLoaded', function () {
$(document).ready(function() {
$('.myButton').click(function(e) {
var searchFeature = ($('#formValueId').val());
request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q='+searchFeature, true);
var next = 1;
var searchFeature = ($('#formValueId').val());
//console.log(searchFeature);
e.preventDefault();
var addto = "#field" + next;
next = next + 1;
var newIn = '<button id="newButton" value='+searchFeature+' onclick="buttonFeature(this.value)">'+searchFeature+'</button>';
var newInput = $(newIn);
$(addto).after(newInput);
request.onload = function() {
for (var i = 0; i <= 10; i++) {
data = JSON.parse(request.responseText).data[i].images.fixed_height.url;
console.log(data);
document.getElementById("searchResults").innerHTML = '<center><img src = "'+data+'" title="GIF via Giphy"></center><br>';
}
};
request.onerror = function() {
console.log('connection error');
};
request.send();
});
});
});
答案 0 :(得分:0)
而不是每次循环时替换图像的innerHTML我使用Jquery就像这个$(&#34;#searchResults&#34;)。追加(&#39;评级:&#39; +评级+&# 39;&#39);