I have few links in a page and I want to add a function to each link. I've done that with a loop.
Now, I got an array of objects. I want to pass objects values to function that I assigned to links. So I want to match links array with my object array.
html
<a href="#">link1</a>
<a href="#">link2</a>
<a href="#">link3</a>
js
var myArray = [
obj1 = {property: "value1"},
obj2 = {property: "value2"},
obj3 = {property: "value3"}
];
var pageLinks = document.getElementsByTagName("a");
for (i = 0, len = pageLinks.length; i < len; i++){
pageLinks[i].attachEvent("onclick", function(i){
alert(myArray[i].property);
}, false);
}
I tried doing this but I think I'm missing something. If I use array index instead of i
in alert()
it works fine. But there's no matching. I'm stuck with just one obj. How can I pass loop
's i
not just to page links but also to my function.
EDIT: I guess I should have mentioned that I'm NEW to JS. I don't even know what closure means in JS. Same goes for bind... Instead of telling me what to do/use you could have just show me how to fix my current problem and link a demo maybe? Since I'm new to JS (don't know all these term) it's kinda hard to get the logic in someone else's code. Anyway. I have an answer now. Thanks.