Jquery - 添加父级

Rob*_*bik 1 html javascript jquery

我是jQuery的新手,我有一个问题.

我有脚本,用于调整某些div中的每个图像.我想将该图像插入到不存在的div中(创建div-parent),怎么样?

编辑:

我有这个代码:

$('#content img').each(function() {

            if( $(this).width() > maxWidth || $(this).height() > maxHeight )
            {   
                var ratio = 0;
                if( $(this).width() > $(this).height() )
                {
                    ratio = maxWidth / $(this).width();
                    $(this).css('width', maxWidth + 'px');
                    $(this).css('height', ( $(this).height() * ratio) + 'px' );
                }
                else
                {
                    ratio = maxHeight / $(this).height();
                    $(this).css('width', ($(this).width() * ratio) + 'px');
                    $(this).css('height', maxHeight + 'px');
                }

                $(this).addClass('scaled-img');
                $(this).wrap('<div class="test"></div>'); // trying to add

            }                               

            });
});
Run Code Online (Sandbox Code Playgroud)

结果:

<img src="path.."/>
Run Code Online (Sandbox Code Playgroud)

我想要的结果:

<div><img src="path"/></div>
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 13

使用.wrap().

HTML

<div id="some-div">
    <img ... />
    <img ... />
    <img ... />
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$(function ()
{
    $('#some-div > img').wrap('<div class="new-parent"></div>');
});
Run Code Online (Sandbox Code Playgroud)

结果

<div id="some-div">
    <div class="new-parent"><img ... /></div>
    <div class="new-parent"><img ... /></div>
    <div class="new-parent"><img ... /></div>
</div>
Run Code Online (Sandbox Code Playgroud)

演示(现在有额外的小猫!)

  • ***额外的小猫+1!***:) ...和整个'有用的答案'的事情,我猜...:/ (2认同)

Poi*_*nty 5

查看“.wrap()”jQuery 方法。它允许您将 en 元素包装在其他一些容器元素中:

$('#myImage').wrap('<div></div>');
Run Code Online (Sandbox Code Playgroud)

如果你需要给容器一些属性:

$('#myImage').wrap($('<div></div>', {
  id: "newWrapper",
  class: 'wrapper banana',
  css: { 'borderColor': 'green', 'borderWidth': '2px' }
}));
Run Code Online (Sandbox Code Playgroud)