我的项目中有一个循环通过JSON文件。我从中检索href和图像的src。但是我需要以特定的方式输出它,如下所示:
<li>
<a href="link1_fromJSON.HTML" data-transition="slidedown">
<img src="image_1_fromJSON.jpg"/>
<h3> Menu1</h3>
</a></li>
<li>
<a href="link2_fromJSON.HTML" data-transition="slidedown">
<img src="image_2_fromJSON.jpg"/>
<h3> Menu2</h3>
</a>
</li>
<li>
<a href="link_3_fromJSON.HTML" data-transition="slidedown">
<img src="image_3_fromJSON.jpg"/>
<h3> Menu3</h3>
</a>
<li>
这是我的javascript代码:
$.each(data.posts, function(index, d){
$("<li>", { html:'<img src="' + d.thumbnail_images.thumbnail.url + '" />' }).appendTo("#div1");
});
我得到的只是一个div中的图像列表。我不知道如何得到我想要的结果。
答案 0 :(得分:1)
您最好将其发布到DOM一次,
var myNewStuff = "";
$.each(data.posts, function(index, d){
myNewStuff = myNewStuff + "<li><img src='" + d.thumbnail_images.thumbnail.url + "' /></li>";
});
$(myNewStuff).appendTo("#div1");
编辑:尝试将href放在没有任何定义的情况下,所以我想在这里:
$.each(data.posts, function(index, d){
myNewStuff = myNewStuff + "<li><a data-transition='slidedown' href='" + d.myhref + "<img src='" + d.thumbnail_images.thumbnail.url + "' /><h3> Menu" + index + "</a></li>";
});
$(myNewStuff).appendTo("#div1");
<强> ANSWER 强>
var myNewStuff = "";
$.each(data.posts, function(index, d){
myNewStuff = myNewStuff + "<li><a data-transition='slidedown' href='" + d.slug + "'><img src='" + d.thumbnail_images.thumbnail.url + "' /><h3> Menu" + index + "</li>";
});
$(myNewStuff).appendTo("#div1");
答案 1 :(得分:1)
这个怎么样:
HTML
<ul id="list"></ul>
的Javascript
$(document).ready(function(){
var data = [
{href: '/url1', img: 'img1.jpg', text: 'text1'},
{href: '/url2', img: 'img2.jpg', text: 'text2'},
{href: '/url3', img: 'img3.jpg', text: 'text3'},
{href: '/url4', img: 'img4.jpg', text: 'text4'}
];
for(var i = 0; i < data.length; i++){
var li = $('<li>');
var h3 = $('<h3>').text(data[i].text);
var im = $('<img/>').attr('src', data[i].img);
var a = $('<a>').attr('href', data[i].href).append(im).append(h3);
$('#list').append(li.append(a));
}
})
答案 2 :(得分:-2)
试试这个..
$("ul").append("<li><a href='url-here'><img src="' + d.thumbnail_images.thumbnail.url + '" /></a></li>");