【发布时间】:2015-11-05 02:11:23
【问题描述】:
我正在编写调整图像大小以适应容器大小的脚本。我写下了以下代码:
$(function () {
$('.postbody .content img').each(function () {
var containerWidth = $(this).parent().width();
if ($(this).width() > containerWidth) {
$(this).width(containerWidth);
$(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank"></a>');
}
});
});
但它只适用于循环中的第一个元素。根据我之前将 jQuery 方法分配给变量的问题的经验,我稍微更改了代码:
$(function (){
$('.postbody .content img').each(function () {
if ($(this).width() > $(this).parent().width()) {
$(this).width( $(this).parent().width() );
$(this).wrap('<a href="'+$(this).attr('src')+'" target="_blank"></a>');
}
});
});
现在它可以完美运行了。但我无法弄清楚如何。 containerWidth 变量不应该在每个循环的每个函数调用中获取新值吗?
编辑:请注意所有容器的大小相同。
【问题讨论】:
-
是的,它会得到更新。但如果该特定代码在页面加载之前运行,则不会。
-
它应该可以工作,你能在演示中创建问题吗.. 唯一的问题是你可能需要等待图像加载
-
上面的脚本在
$(window).load()事件上可以正常工作。到那时所有图像都已加载。因此父div得到它的宽度。我认为问题在于事件而不是变量。
标签: jquery loops variables each behavior