Reputation: 3222
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
Upvotes: 2
Views: 202
Reputation: 3823
As this question marked as duplicate before @blessenm adds his answer, I'm just rewriting my answer so that his elegant solution will be visible to someone looking in this question in the future. I've posted different answer before the question was closed, so I'm still able to edit my answer. All credits to @blessenm:
function start() {
omega.addEventListener("click", function(evt) {
alert([].indexOf.call(evt.currentTarget.children, evt.target));
}, false);
}
[].indexOf is shortcut of Array.prototype.indexOf function. The first argument you're passing is the context, the second argument is the item you're searching in that array. DOM elements array-like objects but are not actual arrays therefore they don't have the array methods in Array.prototype - that's why you cannot use alert(evt.currentTarget.children.indexOf(evt.target)). To do array operations on a DOM we use the call method of Array prototype.
Upvotes: 1