jquery - 所有包含元素的宽度 + 最后一个元素的宽度

标签 jquery width

我需要一个容器 div 作为其所有图像的组合宽度,加上最后一个图像的宽度。我已经得到了组合图像的宽度:

$(window).load(function() {
    $('.pressimage').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
            totalImageWidth += $(this).width();
        });

        $(this).width(totalImageWidth);
    });
});

那么我现在如何添加最后一张图像的宽度?我已经尝试过,但它不起作用:

$(window).load(function() {
    $('.pressimage').each(function() {
        var totalImageWidth = 0;

        $("img", this).each(function () {
            totalImageWidth += $(this).width();
        });


        $("img", this).last(function () {
            lastImageWidth = $(this).width();
        });

        $(this).width(totalImageWidth + lastImageWidth);
    });
});

谢谢

更新。 抱歉,我正在处理错误的代码。这是我所拥有的使 div 成为其所有图像的宽度的方法:

$(window).load(function() {

    var pub_accum_width = 0;

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
        pub_accum_width += $(this).width();
    });
    //alert(pub_accum_width);

        $('.view-public-collection .view-content').width(pub_accum_width);

}); 

这是我修改后的代码,但它并没有使 div 更宽:

$(window).load(function() {


    var pub_accum_width = 0;
    var pub_accum_last = 0;

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
            pub_accum_width += $(this).width();
    });


    $('.view-public-collection .pubimagecolor').find('img').last(function() {
        pub_last_width += $(this).width();
    });


    $('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);


});

谢谢

最佳答案

更新问题的答案:

$(window).load(function() {
    var pub_accum_width = 0;
    var pub_last_width = 0; // not pub_accum_last

    $('.view-public-collection .pubimagecolor').find('img').each(function() {
        pub_accum_width += $(this).width();
    });

    //                                                   ...last(function(...
    $('.view-public-collection .pubimagecolor').find('img').last().each(function() {
        pub_last_width += $(this).width();
    });

    $('.view-public-collection .view-content').width(pub_accum_width + pub_last_width);
});

last()是一个单独的遍历函数,不能为其添加回调参数。选择最后一个元素,然后使用each()。您还使用不同的变量名称。

<小时/>

您必须在 last() 回调 each() 回调之外定义 lastImageWidth 变量last(),以便能够再次在外面使用它。

// ...
var totalImageWidth = 0;
var lastImageWidth = 0;
// ...

关于jquery - 所有包含元素的宽度 + 最后一个元素的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4955559/

相关文章:

javascript - 使用 html 5 注入(inject) jQuery 表

php - javascript 文件返回一个我不确定的错误日志

javascript - 同时使用 scrollTop() 两次

jquery - 如果元素宽度等于 .. 像素,则执行 addClass

.net - 是否可以防止 DataGridView 中出现多行 HeaderText?

jquery - 如何获得单个元素的内部和外部宽度?

javascript - jquery ui 自动完成的绝对路径

jQuery.ajax() 方法的异步选项已弃用,现在怎么办?

html - 找到拉伸(stretch)网页的元素?

css - 固定行跨度和表格布局时的表格列宽