用jQuery交换div内容

Eri*_*ric 8 html javascript jquery swap

这是我的HTML:

<div class="large">
    <img src="/images/photos/Interior.jpg" alt="The interior" style="[...]" />
    <div class="caption">The interior</div>
</div>
<div class="small">
    <img src="/images/photos/Bedroom.jpg" alt="Bedroom" style="[A different ...]" />
    <div class="caption">A bedroom</div>
</div>
Run Code Online (Sandbox Code Playgroud)

单击a后div.small,我想要图像和标题来交换容器div.问题是我不能只交换src,因为有一些需要保留的内联样式集.最后,一旦交换了图像,我想将自定义函数.fitToParent()应用于它们.

我该怎么做呢?

Rop*_*tah 16

$(document).ready(function() {
    $('div.small').click(function() {
        var bigHtml = $('div.large').html();
        var smallHtml = $(this).html();

        $('div.large').html(smallHtml);
        $('div.small').html(bigHtml);

        //custom functions?
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 这很有效但你丢失了绑定到div的任何事件(比如"controlName.change()".使用detach和append会保留事件.请参阅http://stackoverflow.com/a/9719297/1359088 (3认同)