我想完全交换两个html div标签,标签和所有。我尝试了代码下面的代码,但它不起作用。
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id.next().next());
如何完全交换两个div标签。
答案 0 :(得分:2)
您的代码中有一些括号不匹配,看起来您可能正在尝试执行此操作:
jQuery('#AllBlock-'+Id).insertAfter($('#AllBlock-'+Id').next().next());
这将采取类似的措施:
<div id="AllBlock-5"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
并且,如果使用Id 5调用,请将其转换为:
<div id="AllBlock-6"></div>
<div id="AllBlock-7"></div>
<div id="AllBlock-5"></div>
这是因为您正在使用第5块,并将其(使用insertAfter
)移动到距离自身next().next()
(或下一个)的块之后的位置,这将是第7块。
如果您希望始终将#AllBlock-Id
与#AllBlock-[Id+2]
交换,那么他们会切换位置并最终结果如下:
<div id="AllBlock-7"></div>
<div id="AllBlock-6"></div>
<div id="AllBlock-5"></div>
您可能想尝试:
var $block = jQuery('#AllBlock-'+Id);
var $pivot = $block.next();
var $blockToSwap = $pivot.next();
$blockToSwap.insertBefore($pivot);
$block.insertAfter($pivot);
答案 1 :(得分:0)
您无法执行此操作,因为您无法连接字符串和jQuery对象。
试试这个:
var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());
答案 2 :(得分:0)
应该是这样的
你应该在Id之后关闭括号,
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());
答案 3 :(得分:0)
您需要先分离现有的dom对象,然后再重新使用它:
$('#divid').detach().insertAfter('#someotherdivid');
答案 4 :(得分:0)
我的理解是你想用最后一个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/