函数中的 JQuery 变量有奇怪的行为

标签 jquery loops variables each behavior

我正在编写调整图像大小以适应容器大小的脚本。我写下了以下代码:

$(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 变量不应该在每个循环的每个函数调用中获取新值吗?

编辑:请注意,所有容器的大小相同。

最佳答案

试试这个,

$(function () {
    $('.postbody .content').each(function () {
        var containerWidth = $(this).width();
        var img = $(this).find("img");
        if (img.width() > containerWidth) {
            img.width(containerWidth);
            img.wrap('<a href="' + img.attr('src') + '" target="_blank"></a>');
        }
    });
});

或者您可以简单地使用 CSS 执行相同的操作

只需将 img 标签最大宽度设置为 100%

例如。

img {
   max-width: 100%;
}

关于函数中的 JQuery 变量有奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965701/

相关文章:

jquery - Sql 加入 Codeigniter 吗?

带有用户输入的 C 斐波那契数列

在循环中不断检查共享内存是否发生变化

php - 为什么这个对 mysql 结果集的循环很慢? (每个周期 1.4 毫秒)

c++ - 变量的地址需要加载到内存中吗?

excel - 如何创建 ActiveX 控件 CommandButton 并将其设置为变量 Excel VBA

cocoa nsimage 未保存

javascript - jQuery:当一个元素在页面上可见时,仅触发一次函数

javascript - 隐藏所有未选中的列表元素,Ruby 或 JavaScript

javascript - jQuery - 如何使用 .replace 与 jQuery obj