《JavaScript: The Good Parts》讲解闭包的章节中一处代码小错误

39页,给出了一个讲解闭包的代码:

var add_the_handlers=function(nodes){
var i;
for(i=0;i nodes[i].onclick=function(i){
return function(e){
alert(e);
};
}(i);
}
}

这个函数的目的是: Make a function that assigns event handler functions to an array of nodes the right way. When you click on a node, an alert box will display the ordinal of the node.

但是代码中alert的却是'e',这个是event,如果是这样的话,点击每个节点,都是alert的 '[object MouseEvent]'
我们只要把alert(e)改为alert(i)就正确了,就可以alert出这个节点在所有选中的节点中的序数了。





此条目发表在 javascript 分类目录,贴了 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>