交换<div>?</div>

时间:2011-02-06 06:33:23

标签: jquery-ui

这是我的示例代码

<div id="id-1"><div>sampledata</div><span>sampledata</span></div> 
<div id"id-2"><div>sampledata</div><div> smpledata</div></div>
<div id"id-3"><div>sampledata</div><div> smpledata</div></div>
<div id"id-3"><div>sampledata</div><div> smpledata</div></div>

我的id只有一个div(例如id-3)。我想将<div>替换为下一个<div>,因为<div>中有多个<div>我无法使用next()

提前致谢

2 个答案:

答案 0 :(得分:0)

好吧,选择div,然后找到next和insertAfter next

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.js"></script>
<style>
.innderdiv4{
    backgrournd: green;
}

.innderdiv3{
    background: blue;
}
</style>
<script>
$(function (){
    var div = $('#id3');
    var next = $(div).next();
    if(confirm("Are you sure you want to do it"))
    {
        $(div).insertAfter(next);
    }
})
</script>

<div id="container">
<div id="id3">
    <div class="innderdiv3">div 3</div>
    <div class="innderdiv3">div 3</div>
</div>
<div id="id4">
    <div class="innderdiv4">div 4</div>
    <div class="innderdiv4">div 4</div>
</div>
</div>

答案 1 :(得分:0)

.next(); 确实选择下一个兄弟,而不是子div元素。但是,为了确保您选择实际上是div的下一个兄弟,您应该使用.next("div");

$("#id-3").before($("#id-3").next("div"));  

只要您将上一个div的ID更改为“id-4”,上面的代码就会与您提供的示例一起使用。

或者,您可以复制并粘贴此代码以获取工作示例:

<html>
    <head>
        <title>Div Swap Test Page</title>
        <style type="text/css">
            #id-1,#id-2,#id-3,#id-4 {height: 50px; margin:10px 0; border:solid 1px #000}
            #id-3 {border:solid 1px #D00}
            #id-4 {border:solid 1px #0D0}
        </style>
    </head>

    <body>
        <div id="id-1"><div>This is div #1</div><span>I am first.</span></div>
        <div id="id-2"><div>This is div #2</div><span>I am second.</span></div>
        <div id="id-3"><div>This is div #3</div><span>I am third.</span></div>
        <div id="id-4"><div>This is div #4</div><span>I am last.</span></div>
        <p><button id="btn"><span>Swap</span></button></p>
    </body>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        $("#btn").click(function() {
            $("#id-3").before($("#id-3").next("div"));
        });
    });
    </script>
</html>