Edit: Topic has been marked as duplicate. I just wanted to say that im not happy with the answers of the other post. The accepted answer uses a not so nice way of dealing with such problem. Apart from that I made it clear that I read all those posts before and have difficulties understanding that particular problem area in javascript.
I dont get this at all. I really do a lot of reading, especially about closures but I dont get this...im on it for hours. Why does the following code fail to work? Im absolutely lost now and I need someone who could really point out how I can overcome situations like these where my index fails to be recognized within my event function.
How does this work? My addEventListener just wont work since the index is only recognized outside of it.
var lastResponse;
var alpha = document.getElementById('alpha');
var httpRequest;
function initAjax(url) {
httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = httpRequest.responseText;
document.getElementById("omega").innerHTML = response;
fn();
}
}
}
alpha.addEventListener("click", function() {
initAjax("test.php");
});
var x = document.getElementById("omega").children;
function fn() {
for(var i=0; i < x.length; i++){
console.log(x.length);
document.getElementById("omega").addEventListener("click", function(event){
hello(i, event);
}, false);
}
}
function hello(index, event){
console.log(event.currentTarget.children[index]);
}
Updated code
- Ajax gets content with their respective divs
- When request is completed javascript injects the returned data from the server to omega.
- Omega has children.
- Now I want to click on one of those children and get their index.
#omegais the only element that's anevent.target,is in a loop, why ? I think you need to include the HTML, because I'm having a hard time trying to visualize abutton#omega? Thesechildrenof#omegaare what and how many?