编辑:主题已被标记为重复。我只是想说我对其他帖子的答案不满意。接受的答案使用一种不太好的方式来处理此类问题。除此之外,我明确表示我之前阅读了所有这些帖子并且很难理解 javascript 中的特定问题区域。
我完全不明白这个。我真的读了很多书,尤其是关于闭包的书,但我没读懂这个……我花了好几个小时。为什么以下代码无法运行?我现在完全迷路了,我需要有人能够真正指出我如何克服像我的索引无法在我的事件函数中被识别的情况。
这是如何运作的?我的 addEventListener 无法正常工作,因为索引只能在其外部识别。
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]);
}
更新代码
- Ajax 通过各自的 div 获取内容
- 当请求完成时,javascript 将从服务器返回的数据注入(inject) omega。
- Omega 有 child 。
- 现在我想点击其中一个 child 并获取他们的索引。
最佳答案
由于这个问题在@blessenm 添加他的答案之前被标记为重复,所以我只是重写我的答案,以便将来查看这个问题的人可以看到他的优雅解决方案。在问题关闭之前我已经发布了不同的答案,所以我仍然可以编辑我的答案。所有学分@blessenm:
function start() {
omega.addEventListener("click", function(evt) {
alert([].indexOf.call(evt.currentTarget.children, evt.target));
}, false);
}
[].indexOf 是 Array.prototype.indexOf 函数的快捷方式。您传递的第一个参数是上下文,第二个参数是您在该数组中搜索的项目。 DOM 元素类似于数组对象,但不是实际数组,因此它们在 Array.prototype 中没有数组方法——这就是为什么不能使用 alert(evt.currentTarget.children.indexOf(evt.target)) 的原因。要对 DOM 进行数组操作,我们使用数组原型(prototype)的调用方法。
关于Javascript addEventListener 不适用于 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34553462/