我写了这段代码:
(function($) {
$.fn.extend({
videoGallery: function() {
this.each(function() {
gallery = $(this); // present object in the $.each iteretor
$(this).find('a').click(function(e){
e.preventDefault();
alert( gallery.attr('id') );
});
});
}
});
})(jQuery);
$('.video-gallery').videoGallery();为什么,当我单击"a“元素时,var库总是具有相同的值,并且它对应于$.each迭代器中的最后一个库?
谢谢,对不起,我的英语不是我的母语
发布于 2011-11-29 06:52:49
您错过了var关键字,请尝试
...
var gallery = $(this);也许这就是问题所在。
发布于 2011-11-29 07:04:27
这就是闭包的工作方式。gallery变量是全局的(不小心?)并且您在每次迭代中都分配了一个新值,因此当任何单击事件被触发并且循环完成时,库就是循环中的最后一个。尝试如下所示:
$(this).find('a').click((function(gallery) {
return function(e){
e.preventDefault();
alert( gallery.attr('id') );
};
}(gallery)));您还可以使用var gallery = $(this)将其赋给循环闭包内的局部变量。
https://stackoverflow.com/questions/8303499
复制相似问题