开发者

How to swap two div tags?

I want to swap two html div tags entirely, tags and all. I tried the code below code but it does not work.

jQuery('#All开发者_如何转开发Block-'+Id).insertAfter('#AllBlock-'+Id.next().next());

How to swap two div tags entirely.


You have some bracket mismatching in your code, it looks like you might be trying to do this:

jQuery('#AllBlock-'+Id).insertAfter($('#AllBlock-'+Id').next().next());

Which would take something like:

<div id="AllBlock-5"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>

And, if called with Id 5, turn it into this:

<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
<div id="AllBlock-5"></div>

This is because you're taking block 5, and moving it (using insertAfter) to the place after the block that's next().next() (or next-but-one) from itself, which would be block 7.

If you want to always swap #AllBlock-Id with #AllBlock-[Id+2], so they switch places and end up like the following:

<div id="AllBlock-7"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-5"></div>

You might want to try:

var $block = jQuery('#AllBlock-'+Id);
var $pivot = $block.next();
var $blockToSwap = $pivot.next();
$blockToSwap.insertBefore($pivot);
$block.insertAfter($pivot);


You can't do this because you can't concatenate a string and a jQuery object.

Try this:

var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());


it should be like this

you should close the bracket after Id,

jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());


You'll need to detach the existing dom object first, then re-use it later:

$('#divid').detach().insertAfter('#someotherdivid');


What I understand is you want to swap a div when clicked with the last div. What will you do if it is the last div? move it to the top?

This solution should solve the problem, furthermore, you can modify this regex to match the format of your ID. This can probably be made more concise and robust. For example, you could get the last ID a bit more sophisticatedly. This may just be modifying the selector or something more. I mean, you do not want to go rearranging the footer or something just because its the last div on the page.

$('div').click(function() {

//set regex
var re = /(^\w+-)(\d+)$/i;

//get attr broken into parts
var str = $(this).attr('id').match(re)[1], 
    id  = $(this).attr('id').match(re)[2];


//get div count and bulid last id 
var lastStr = $('div:last').attr('id').match(re)[1],
lastID = $('div:last').attr('id').match(re)[2];


//if we have any div but the last, swap it with the end
if ( id !== lastID ) {
       $(this).insertAfter('#'+lastStr+lastID);
}

//otherwise, move the last one to the top of the stack
else {
    $(this).insertBefore('div:first');
} });

Check out this working fiddle: http://jsfiddle.net/sQYhD/

You may also be interested in the jquery-ui library: http://jqueryui.com/demos/sortable/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜