的可能的误解基本上我有一些事件侦听器及其处理函数定义如下:的JavaScript循环越过环约束,封
<div id="postTextBlock"/>
<div id="postImageBlock"/>
<div id="postQuoteBlock"/>
<div id="postLinkBlock"/>
document.getElementById('postTextBlock').addEventListener('click', function() { showPostType(postTextBlock) }, false);
document.getElementById('postImageBlock').addEventListener('click', function() { showPostType(postImageBlock) }, false);
document.getElementById('postQuoteBlock').addEventListener('click', function() { showPostType(postQuoteBlock) }, false);
document.getElementById('postLinkBlock').addEventListener('click', function() { showPostType(postLInkBlock) }, false);
var showPostType = (function() {
var postTypes = new Array('postTextBlock', 'postImageBlock', 'postQuoteBlock', 'postLinkBlock')
return function(type) {
for (var i = 0; i < postTypes.length; i++) {
(function(index) { alert(document.getElementById(postTypes[index])) })(i)
}
}
})()
当我运行此我将获得5个警报。一个用于我的数组中定义的每个postTypes,以及我猜测的最终空值是postTypes[5]
。为什么在i = 5
(postTypes.length
= 4)设置for循环终止时,它执行i = 5
的代码。
编辑: 我添加了它引用的html以及完整的数组值。希望这会清除一些有关代码无法工作的内容。
你确定长度是'4'吗?有一个非常基本的循环它的工作原理:http://jsfiddle.net/tbGYV/,所以我猜错误是在'postTypes.length'和/或它找不到该元素。 – 2010-10-27 09:48:39
你是否覆盖了你的数组构造函数? – helle 2010-10-27 09:49:30
Felix Kling:是的,它的4.我在调试器中多次检查过它。我不知道为什么。我第一次遇到错误时做的第一件事就是使用您发布的基本循环。 – PolandSpring 2010-10-27 09:57:51