我的代码需要帮助。我想要一个上一个和下一个按钮,这些将调用函数viewBlogItem(direction,cat,blogid);
在该函数中,我将读取json文件,并按“类别”进行分类。
每个blogItem都有一个articleid和一个类别,如果单击“下一步”按钮,我想拥有下一个blogItem.articleid并显示该博客对象(我对那个对象使用append)。如果direction ==“ next”,则查找是否有类别中的下一项,如果没有,则隐藏$('。next')。前一个按钮$('。previous')也是如此
blogItems.json
{
"blogItem":[
{
"id": 1,
"title": "animals blog 1",
"category":"animals",
"text":"text",
"articleid":1
},
{
"id": 2,
"title": "lifestyle blog 1",
"category":"lifestyle",
"text":"text",
"articleid": 1
},
{
"id": 3,
"title": "animals blog 2",
"category":"animals",
"text":"text",
"articleid": 2
},
{
"id": 5,
"title": "animals blog 4",
"category":"dieren",
"text":"text",
"articleid":4
},
{
"id": 4,
"title": "animals blog 5",
"category":"animals",
"text":"text",
"articleid":3
}
]
}
jQuery的
function viewBlogItem(direction,cat,blogid) {
var id = "";
if(direction == "next"){
// code for showing next blogitem
//if no next then
$('').hide();
}
else{
// if no previous then hide
//code for showing previous blogitem
}
loadBlog(id);
}
function loadBlog(blogid){
$.getJSON('blogitems.json', function (data) {
$.each(data.blogItem, function (i, item) {
if (item.id == blogid) {
$('.view').append('all sorts of stuff');
return;
}
});
});
}
我还想对我的json的结构提出一些建议。
我怎么能知道之前或之后的另一个博客?
查看当前博客项目的索引,查看下一个是否大于数组中的项目数,或者前一个小于0。
var blogs = {
"blogItem": [{
"id": 1,
"title": "animals blog 1",
"category": "animals",
"text": "text",
"articleid": 1
}, {
"id": 2,
"title": "lifestyle blog 1",
"category": "lifestyle",
"text": "text",
"articleid": 1
}, {
"id": 3,
"title": "animals blog 2",
"category": "animals",
"text": "text",
"articleid": 2
}, {
"id": 5,
"title": "animals blog 4",
"category": "dieren",
"text": "text",
"articleid": 4
}, {
"id": 4,
"title": "animals blog 5",
"category": "animals",
"text": "text",
"articleid": 3
}]
};
var index = 0;
var item = blogs.blogItem[index];
var title = document.getElementById('title');
var text = document.getElementById('text');
var previous = document.getElementById('previous');
var next = document.getElementById('next');
displayItem(item);
previous.addEventListener('click', function() {
displayItem(blogs.blogItem[--index]);
});
next.addEventListener('click', function() {
displayItem(blogs.blogItem[++index]);
});
function displayItem(item) {
title.innerText = item.title;
text.innerText = item.text;
previous.disabled = index <= 0;
next.disabled = index >= blogs.blogItem.length -1;
}
[disabled] {
opacity: 0.5;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
<div>
<div id="title"></div>
<div id="text"></div>
</div>
<button id="previous">Previous</button>
<button id="next">Next</button>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句