Javascript for loop goes over loop constraint, possible misunderstanding of closure
Basically I have some event listeners and their handling function defined as follows:
<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)
开发者_JS百科 }
}
})()
When I run this I will get 5 alerts. One for each of the postTypes defined in my array and a final null for what I'm guessing is postTypes[5]
. Why is it executing the code with i = 5
when I have set the for loop to terminate when i = 5
(postTypes.length
= 4).
Edit: I added the html that it references as well as the full array values. Hopefully this clears some stuff up about the code not working.
You know your code sample doesn't work? I took a stab at what it's --supposed-- to do.
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);
The arguments passed above were not included, based on the function code they did nothing anyways.
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);
}
}
})()
I added some trickery as just an example of a better way to write a for loop. Your closure works fine, I think you are doing something else to cause this code to not work as expected. Why would this error run 4 times, there's only two items in the array. My example ran exactly twice every time I clicked a div, as you can see on JSFiddle.
The div's id is "postLInkBlock", but you're searching for "postLinkBlock". That's the null.
精彩评论