if index > 0: loop; else: do only once (JSON & jQuery)
I have been doing some customization to this jQuery paging script I found here Paging Through Records Using jQuery
I've got the paging working nicely, and it is handling different javascript responses appropriately.
I have one problem though. The response is expecting the JSON to have an index/array.
90% of the time, I have multiple entries in my JSON, but sometimes I have only one item being returned. This results in zero entries.
Here is the code I've got
var pagedContent = {
data: null
,holder: null
,currentIndex : 0
,init: function(data, holder) {
jQuery("body").data(holder,data);
this.holder=holder;
this.show(0, holder); // show last
}
,show: function(index, holder) {
this.data=jQuery("body").data(holder);
if(!this.data){
return;
}
var j=2;
if(this.data.length-index<=j){
j=this.data.length-index-1;
}
var jsonObj = this.data[index];
if(!jsonObj) {
return;
}
var holdSubset="";
for(i=0;i<=j;i++){
jsonObj=this.data[index+i];
this.currentIndex = index;
if(this.holder=="id1"){
var theResultVariables = jsonObj.whatever
var resultInput='<div class="putstuff">'+theResultVariables+'</div>';
}
if(this.holder=="id2"){
var theResultVariables = jsonObj.whatever
var resultInput='<div class="putstuff2">'+theResultVariables+'</div>';
}
holdSubset= holdSubset+resultInput;
}
jQuery("body").html("<div id=\"counter\">"+parseFloat(index+1)+" to "+ parseFloat(index+j+1)+" of "+this.data.length+"</div>"+holdSubset+"<div class=\"prevNext\"></div>");
if(index!=0){
var previous = jQuery("<a >").attr("href","#").click(this.previousHandler).text("< previous").data("whichList",this.holder).data("thisIndex",index - 2-1);
jQuery("body").append(previous);
}
if(index+i<this.data.length){
var next = jQuery("<a class=\"next\">").attr("href","#").click(this.nextHandler).text("next >").data("whichList",this.holder).data("thisIndex",index + 2 +1);
jQuery("body").append(next);
}
}
,nextHandler: function() {
pagedContent.show(jQuery(this).data("thisIndex"), jQuery(this).data("whichList"));
return false;
}
,previousHandler: function() {
pagedContent.show(jQuery(thi开发者_如何学运维s).data("thisIndex"), jQuery(this).data("whichList"));
return false
}
};
I know that I can add another check
var jsonObj = this.data[index];
if(!jsonObj){
var jsonObj=this.data;
}
if(!jsonObj) {
return;
}
and then lower down
jsonObj=this.data[index+i];
if(!jsonObj){
jsonObj=this.data;
}
But I don't think that is probably the most efficient way to do it. Any ideas?
Since you're using jQuery, take a look at jQuery.makeArray. It takes an array or a scalar, and returns an array. If you add a call like this in as a preceding step:
this.data = jQuery.makeArray(this.data);
You won't have to worry about if it's a scalar or an array. Scalars will be converted to arrays of length 1.
精彩评论