【发布时间】:2015-10-16 13:38:09
【问题描述】:
我正在尝试使用 mansory.js 创建一个类似 pinterest 的网页,但我无法将唯一描述附加到每个图像。我知道我的代码的最后一行是错误的,但我不知道如何修复它。我基本上是将所有描述标签添加到每个图像的一个跨度中。
我尝试查看其他几个 stackoverflow 问题,例如 jQuery: Add element after another element 和 add image/s inside a div with jquery 但没有运气。
我的整支笔都在这里http://codepen.io/OG/pen/VLEXgz
HTML
<body>
<h1>Camper Stories</h1>
<div id="content"></div>
</body>
CSS
h1{
text-align:center;
font-family: 'Lobster', cursive; font-size:80px;
color:purple;
}
#content {
width: auto;
margin: 0 auto;
}
.item {
display: inline-block;
float: left;
width: 300px;
height:300px;
margin: 2em;
position:relative;
}
.item img {
width: 300px;
height: auto;
}
JS
var url = 'http://www.freecodecamp.com/stories/hotStories';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var i;
var headlines = [];
//loop through json get need attributes
//for(i = 0; i < arr.length; i++){
for (i = 0; i < 5; i++) {
var headline = arr[i].headline;
headlines.push(headline);
var authorImg = arr[i].author.picture;
//console.log(img);
//error function
//if there is no thumbnail link the get author image
if (img === "") {
$('#content').append('<div class="item">' + '<a href="' + link + '">' + '<img id="myImg" src="' + authorImg + '" alt="' + headline + '" />' + '</a>' + '</div>');
} else {
//if there is a thumbnail image then use that image
$('#content').append('<div class="item" id="hi">' + '<a href="' + link + '">' + '<img id="myImg" src="' + img + '" alt="' + headline + '" />' + '</a>' + '</div>');
//if there is a 404 error with loading the thumbnail image then use author's image
$('img').one('error', function () {
this.src = '' + authorImg;
})
}
$(arr[i].headline).insertAfter("img");
}
}
【问题讨论】:
-
发布来自 ajax 的示例响应和预期的 HTML 输出。
-
我认为您应该对此进行更多研究, var hl = $("").text(arr[i].headline); $("img").append(hl);
-
当你有 jQuery 可用时,为什么你使用
XMLHttpRequest? -
@TheGeekYouNeed 你不能在
<img>上附加一些东西,它们没有内容。 -
使用
<figure>和<figcaption>- The figure & figcaption elements
标签: javascript jquery html css