I'm looking to streamline my webpage's code by reading an XML file that contains a variable number of objects. In my JavaScript code, I create an array to store each object and loop through the XML data to generate them.
As I iterate through the XML nodes to create objects and their functions (such as mouseover, onclick, etc.), I encounter an issue. I use the same index variable in these functions to access the current object's properties. However, when the function is triggered, the index variable is no longer within the correct range.
Is there a way for me to retrieve the key (index) value of the calling object?
for (index = 0; index < scenes.length; index += 1) {
this.thumbs[index] = document.createElement('div');
// set up more properties
this.thumbs_image[index] = document.createElement('img');
// more setup
this.thumbs[index].onmouseover = function() {
me.thumbs_image[index].src = scenes[index].attributes.getNamedItem("src").nodeValue;
// THIS IS THE ISSUE - The index is incorrect when the function is executed.
}
}
The code outside of the onmouseover function works fine, and if I hardcode the index inside onmouseover, it also works.
I've tried creating a separate function with the index passed as a parameter, but even when dynamically assigning the function, I still struggle with using the appropriate index:
this.thumb[index].onmouseover = myFunction(index);
function myFunction(i) {
me.thumbs_image[i].src = scenes[i].attributes.getNamedItem("src").nodeValue;
}
Is there any way to obtain the key of the element calling onmouseover?
I'm hoping there's a simple solution that I might have overlooked. Any advice would be greatly appreciated!
Thank you!