如何交换两个div标签?

我想完全交换两个html div标签,标签和所有。 我尝试了代码下面的代码,但它不起作用。

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

如何完全交换两个div标签。

您的代码中有一些括号不匹配,看起来您可能尝试这样做:

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

这会是这样的:

 

并且,如果使用Id 5调用,请将其转换为:

 

这是因为你正在使用块5,并将它(使用insertAfter )移动到自身next().next() insertAfter next().next() (或next-but-one)的块之后的位置,这将是块7。

如果你想总是用#AllBlock-[Id+2]交换#AllBlock-Id ,那么他们会切换位置并最终如下:

 

您可能想尝试:

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

您无法执行此操作,因为您无法连接字符串和jQuery对象。

试试这个:

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

它应该是这样的

你应该在Id之后关闭括号,

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

您需要先分离现有的dom对象,然后再重新使用它:

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

我的理解是你想在点击最后一个div时交换一个div。 如果它是最后一个div你会怎么做? 把它移到顶部?

此解决方案应该可以解决问题,此外,您可以修改此正则表达式以匹配您的ID格式。 这可能会更简洁和健壮。 例如,您可以更复杂地获取最后一个ID。 这可能只是修改选择器或更多。 我的意思是,你不想重新排列页脚或其他东西只是因为它是页面上的最后一个div。

 $('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'); } }); 

看看这个工作小提琴: http : //jsfiddle.net/sQYhD/

您可能也对jquery-ui库感兴趣: http : //jqueryui.com/demos/sortable/