原理是通过监听url锚的更变来渲染json数据里对应的id的内容
使用实例如下
创建json
{"slist":{
"group_111":{
"name":"单选题",
"descript":"本题型共2题,每小题10分,共20分",
"testIds":[1601,1603]
},
"group_555":{
"name":"多选题",
"descript":"本题型共1题,每小题20分,共20分",
"testIds":[1701]
},
"group_666":{
"name":"填空题",
"descript":"本题型共1题,每小题30分,共30分",
"testIds":[1503]
}
}
}
// 使用 location.hash 属性来修改锚部分
function changePart(id) {
location.hash = id;
}
// 锚点改变后要执行的函数
function myFunction(){
var hasNum = getId();
var _data = data.msg;
var _item = _data[hasNum];
render(_item);
}
//地址栏#id
function getId(){
var id = window.location.hash;
if(id){
return id.replace('#','');
}else{
return 0;
}
}
// 渲染页面
function render(d){
var _html = ’’;
$.each(d.slist,function(k,v){
_htmlList += '<li>';
_htmlList += '<h3>'+ v.name +'</h3>';
_htmlList += '<h3 class="sub-introduce">'+ v.descript +'</h3>';
for(var i =0; i < v.testIds.length; i++){
var testId = "xes_"+v.testIds[i];
var _num = _examId.indexOf(testId) +1;
_htmlList +='<button data-id="'+v.testIds[i]+'" class="examlist-btn">' + _num +'</button>'
}
_htmlList += '</li>'
})
$("body").html(html);
}
$(function(){
$('body').on('click','.next-page',function(){
var hasNum = getId();
var _d = data.msg,
_i = Number(hasNum)+1;
if(_i < _d.length){
changePart(_i);
}else{
return false;
}
});
$('body').on('click','.previous-page',function(){
var hasNum = getId();
var _d = data.msg,
_i = Number(hasNum)-1;
if(_i >=0 && _i < _d.length){
changePart(_i);
}else{
return false;
}
});
var hasNum = getId();
var _data = data.msg[hasNum];
render(_data);
// 调用hashchange
if(window.addEventListener){
window.addEventListener("hashchange", myFunction,false);
}else if(window.attachEvent){
window.attachEvent("hashchange", myFunction);
}
})