使用 jquery 将宽度和高度添加到动态 div

Adding width and height to dynamic div with jquery

我在 jquery 中插入一个 div 到一个图像包装器中,基于一个条件(这不重要),我按照它应该的方式工作,但问题是我想给这个 div 一个宽度和一个高度,具体取决于它之前的兄弟图像。 不确定是否可以像我在 jquery 中创建的 div 那样添加宽度和高度。

<div class="imageWrap imageWrap2">
    <img src="images/image1" class="image" />
</div>

使用代码,标记如下所示:

<div class="imageWrap imageWrap2">
    <img src="images/image1" class="image" />
    <div class="extraDiv"></div><-- <-- added with jquery -->
</div>

jquery 我已经添加了(同样,条件并不重要,之后的放置、追加插入等也不重要)

$('.image').each(function(){

    if ($(this).closest('.imageWrap').hasClass('imageWrap'){

        $(this).after('<div class="extraDiv"></div>');

            var imageWidth = $(this).prev().width();
            var imageHeight = $(this).prev().height();

            $('.extraDiv').width(imageWidth).height(imageHeight);       

    }

});

谁能告诉我如何获取每个图像的宽度并将其应用于 extraDiv。

非常感谢。

试试这个? (很难知道它是否可以在没有 fiddle 或 plunkr 的情况下工作):

$('.image').each(function(){
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();
    $(this).closest('.imageWrap').append('<div class="extraDiv"></div>');
    $(this).siblings('.extraDiv').width(imageWidth);
    $(this).siblings('.extraDiv').height(imageHeight);
});

或:

$('.image').each(function(){
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();
    $(this).closest('.imageWrap').append('<div class="extraDiv" style="width:' + imageWidth + 'px;height:' + imageHeight + 'px;"></div>');
});

Plunkr

所以首先你真的不需要那里的 if 语句,因为通过应用 closest(className) 函数你已经在检查它是否有那个 class 名称。此外,运行 会因 if 中的最后一条语句而陷入困境,因为 $('.extraDiv') 将更新所有 classes 并将其作为 extraDiv class,我认为这不是您想在此处执行的操作。