September 19, 201115 yr Hi, Sorry asking a question on my first post, but this problem has been bugging me for a while. I have some Javascript and what I want it do is read through a load of links on a webpage (they have been generated in PHP - that part is working fine) and create an array. This array is called 'elements' in the code and it loads up fine. The problem is I want to update the global variable 'currentPhoto' with element.arrayNo - I have used an alert to pull out the arrayNo in the script and it is definitely there, however when I try to use that number and change the global variable currentPhoto it doesn't update. I'm using currentPhoto as an array index pointer for an image gallery. I need it so I can keep track of where in my array a user is looking. Here is the code: var className; var nextLink; var currentPhoto; var elements; window.onload = initFunctions; function setCurrentPhoto(k) { currentPhoto = k; } function returnCurrentPhoto() { return currentPhoto; } function initFunctions() { elements = document.getElementById('leftContent').getElementsByTagName('a'); //nextLink.onclick = clickNext(this, window.currentPhoto); for (var i=0; i< elements.length; i++) { elements.arrayNo = i; //set an attribute for index of array. elements.linkAdd = "index.php?photo=" + elements.className; elements.onclick = function() { //onclick only kicks in once the array has been set up meaning that all variables are assigned at the end. var id = this.id; var className = this.className; this.href = this.linkAdd; //will only assign link once clicked currentPhoto = this.arrayNo; } } nextLink = document.getElementById('next'); nextLink.onclick = function () { this.href = elements[j].linkAdd; setCurrentPhoto(elements[j].arrayNo); } } function clickNext(object) { } If you need any further information please let me know, and any help would be really great. I'm guessing this problem is to do with closures but I'm not sure. Cheers.
Create an account or sign in to comment