Jquery:在容器内交换容器

时间:2013-11-28 04:24:58

标签: jquery containers

还在学习jquery。我想在父div中交换标题和图像。有任何想法吗?非常感谢!

<div id="main">
<div class="image">IMAGE</div>
<div class="title">TITLE</div>
</div>

<div id="main">
<div class="image">IMAGE</div>
<div class="title">TITLE</div>
</div>

<div id="main">
<div class="image">IMAGE</div>
<div class="title">TITLE</div>
</div>

--------------------------------------------

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#main div").each(function(){
  $("#main").append($('.image'));

});
});
</script>

3 个答案:

答案 0 :(得分:0)

试试这个: - http://jsfiddle.net/adiioo7/YzXye/

此外,您不应该使用具有相同ID的多个元素。

<强> JS: -

$(document).ready(function () {
    $(".main").each(function () {
        $(this).append($(this).find('.image'));

    });
});

<强> HTML: -

<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>
<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>
<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>

答案 1 :(得分:0)

首先将id转换为class,因为id必须为unique并尝试此类似,

<强> HTML

<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>
<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>
<div class="main">
    <div class="image">IMAGE</div>
    <div class="title">TITLE</div>
</div>

<强> SCRIPT

$(document).ready(function(){
   $(".main").each(function(){
       $image= $(this).find('.image');
       $clone=$image.clone();
       $image.remove();
       $(this).append($clone);
   });
});

$(document).ready(function () {
    $(".main").each(function () {
        $(this).find('div.title').after($(this).find('div.image'));
    });
});

DemoDemo 1

答案 2 :(得分:0)

修复ID /类问题后,这是一个简短的解决方案:

$(".main").each(function () {
    $(this).find('div:eq(1)').after($(this).find('div:eq(0)'));
});

<强> jsFiddle example