該代碼允許用戶輸入搜索詞,然後從Flickr中呈現一系列具有該標籤的圖像。這按預期工作,但我不明白爲什麼這會產生如此多的img標籤。爲什麼這段代碼添加空的img標籤?
var main = function() {
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=catss&lang=en-us&format=json&jsoncallback=?";
var $searchInput = $("<input>");
$("header").append($searchInput);
$.getJSON(url, function (flickrResponse) {
flickrResponse.items.forEach(function (photo) {
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
$searchInput.on("keypress", function (event) {
if (event.keyCode === 13) {
$img.remove();
$img.removeAttr('src');
var $tag = photo.tags.split(" ");
$tag.forEach(function (tag) {
if (tag === $searchInput.val()) {
$img.attr("src", photo.media.m);
}
});
$("main .photos").append($img);
$img.fadeIn();
}
});
$("main .photos").append($img);
$img.fadeIn();
});
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
alert("Request Failed: " + err);
});
};
$(document).ready(main);
在上面的代碼的結果:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<body>
<header><input></header>
<main>
<div class="photos">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="" src="http://farm9.staticflickr.com/8299/7875996296_734b9c599d_m.jpg">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
<img style="">
</div>
</main>
<footer> </footer>
<script src="http://code.jquery.com/jquery-2.1.4.min.js">
<script src="javascripts/app.js">
</body>
</html>
爲什麼它被添加這麼多的img標籤?
東陽flickrResponse.items.forEach'的'。如果您經過幫助,請使用您的代碼創建一個小提琴。 – lshettyl
小提琴的意思是使用這個網站http://jsfiddle.net或其他類似的向我們展示一個〜工作示例 –
[代碼在小提琴](https://jsfiddle.net/v1s3kdau/#&togetherjs=PxoTvdbvwG)以及我已經添加代碼小提琴,但我有一個問題,讓它運行。 – tasqyn