2010-10-27 36 views
1

的可能的误解基本上我有一些事件侦听器及其处理函数定义如下:的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 = 5postTypes.length = 4)设置for循环终止时,它执行i = 5的代码。

编辑: 我添加了它引用的html以及完整的数组值。希望这会清除一些有关代码无法工作的内容。

+0

你确定长度是'4'吗?有一个非常基本的循环它的工作原理:http://jsfiddle.net/tbGYV/,所以我猜错误是在'postTypes.length'和/或它找不到该元素。 – 2010-10-27 09:48:39

+0

你是否覆盖了你的数组构造函数? – helle 2010-10-27 09:49:30

+0

Felix Kling:是的,它的4.我在调试器中多次检查过它。我不知道为什么。我第一次遇到错误时做的第一件事就是使用您发布的基本循环。 – PolandSpring 2010-10-27 09:57:51

回答

0

你知道你的代码示例不起作用吗?我刺杀了它所要做的事情。

http://jsfiddle.net/8xxQE/1/

document.getElementById('postTextBlock').addEventListener('click', function() { 
    showPostType('postTextBlock'); //Argument does nothing 
}, false); 
document.getElementById('postImageBlock').addEventListener('click', function() { 
    showPostType('postImageBlock'); //Argument does nothing 
}, false); 

上面传递的参数没有列入的基础上,他们什么也没做,反正功能代码。

var showPostType = (function() { 
    var postTypes = new Array('postTextBlock', 'postImageBlock') 

    return function(/*type argument removed isn't referenced*/) { 
     var l = postTypes.length; 
     for (; l--;) { 
      (function(index) { 
       console.log(index, postTypes[index]); 
       alert(document.getElementById(postTypes[index])) 
      })(l); 
     } 
    } 
})() 

我添加了一些技巧,只是一个更好的方法来写for循环的例子。你的关闭工作正常,我认为你正在做其他事情导致此代码无法按预期工作。为什么这个错误会运行4次,数组中只有两个项目。我的示例每次单击div时都会运行两次,就像您在JSFiddle上看到的一样。

+0

我张贴的代码有些注释,我想这不是很清楚什么被遗漏了。我已经添加了其余的代码,所以事情会更加清晰。 – PolandSpring 2010-10-27 20:12:09

+0

有一段时间,我想我在运行代码时也看到了5条警报,但是后来证明我算错了。 – palswim 2010-10-27 22:54:24

0

该div的ID是“postLInkBlock”,但您正在搜索“postLinkBlock”。那是空的。

+0

这只是示例代码中的一个错字。我得到5个分立警报。 – PolandSpring 2010-10-27 22:34:20