【发布时间】:2020-04-10 10:52:23
【问题描述】:
我正在构建一个随机 DogAPI 图像生成器,您将一个 1-50 的数字放入表单文本框中,点击发送,它会显示该数量的随机狗照片。
我快到了。如果您在文本字段中输入“1”,它将返回 1 个随机图像!但问题是当你放 2 个或更多时。它可以很好地打印到控制台,以指向这些图像的链接的形式显示您选择的数字,但在主页上,它显示了一个损坏的图像链接。它们都在数组内部,在对象内部……我只是对如何在对象中显示所有图像而不是单独显示 1 个图像感到困惑。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>How Many?</title>
<link rel="shortcut icon" href="#">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>How Many Dog Pics Do You Want?</h1>
<p>Pick a number between 1-50</p>
<form>
<input class="number" value="3" type="text" placeholder="1-50?" required>
<input type ="submit" value="Show me the doggies!">
</form>
<section class="results hidden">
<h2>Here you go!</h2>
<img class="results-img" alt="placeholder">
</section>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
CSS:
* {
box-sizing: border-box;
}
body {
font-family: 'Roboto', sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
}
.hidden {
display: none;
}
JS:
'use strict';
function getDogImage(text) {
fetch(`https://dog.ceo/api/breeds/image/random/${text}`)
.then(response => response.json())
.then(responseJson => displayResults(responseJson));
}
function watchForm() {
$('form').submit(event => {
event.preventDefault();
var text = $('.number').val();
if(text < 50){
getDogImage(text);
}else{
alert('Number must be between 1-50')
};
});
}
function displayResults(responseJson) {
console.log(responseJson);
//replace the existing image with the new one
$('.results-img').replaceWith(
`<img src="${responseJson.message}" class="results-img">`
)
//display the results section
$('.results').removeClass('hidden');
}
$(function() {
console.log('App loaded! Waiting for submit!');
watchForm();
});
【问题讨论】:
-
您可以发布您要返回的对象吗?如果 number > 1,您将不得不循环遍历整个对象以提取图像
-
@JoeZ
{ message: [ 'https://images.dog.ceo/breeds/rottweiler/n02106550_12828.jpg', 'https://images.dog.ceo/breeds/sheepdog-english/n02105641_6875.jpg', 'https://images.dog.ceo/breeds/terrier-lakeland/n02095570_4656.jpg' ], status: 'success' }
标签: javascript jquery html json object