Specific Number Of Elements In Loop Are Not Selecting If Data Retrieving From Json Or Xmlhttprequest In Javascript
Looking for selection of next few elements by onclick on 'next' button and selection of previous few elements by onclick on 'previous' button. This works if its static data like he
Solution 1:
It solved. The 'out' variable must be declared in global scope and the selectItems(), nextfun and prevfun must be outside the myFunction(arr)
var myArray = [ { "display": "link 1", "url": "http://www.link1.com" }, { "display": "link 2", "url": "http://www.link2.com" }, { "display": "link 3", "url": "http://www.link3.com" }, { "display": "link 4", "url": "http://www.link4.com" }, { "display": "link 5", "url": "http://www.link5.com" }, { "display": "link 6", "url": "http://www.link6.com" },{ "display": "link 7", "url": "http://www.link7.com" }, { "display": "link 8", "url": "http://www.link8.com" }, { "display": "link 9", "url": "http://www.link9.com" }, { "display": "link 10", "url": "http://www.link10.com" }, { "display": "link 11", "url": "http://www.link11.com" } ];
myFunction(myArray);
var out;
functionmyFunction(arr) {
out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
var next = document.getElementById("next"),
prev = document.getElementById("prev"),
list = document.getElementById("list");
var li = document.getElementById("id01").getElementsByTagName("A");
var currentIndex = 0, amount = 3, len = li.length;
var selectItems = function() {
for (var i=0; i < len; i++) {
li[i].style.background = (i >= currentIndex && i < currentIndex + amount) ?
"red": "yellow";
}
prev.disabled = currentIndex - amount < 0;
next.disabled = currentIndex + amount > len;
};
var prevfun = function() {
currentIndex-=amount;
selectItems();
};
var nextfun = function() {
currentIndex+=amount;
selectItems();
};
selectItems();
#id01{ width:300px; } a{ height:25px;line-height:23px; width:300px; padding:5px; text-decoration:none;float:right; }
<divid="id01"></div><buttonid="prev"onclick="prevfun()">PREVIOUS 3</button><buttonid="next"onclick="nextfun()">NEXT 3</button>
Post a Comment for "Specific Number Of Elements In Loop Are Not Selecting If Data Retrieving From Json Or Xmlhttprequest In Javascript"