【问题标题】:How to swap two div tags?如何交换两个 div 标签?
【发布时间】:2011-05-04 07:31:33
【问题描述】:
我想完全交换两个 html div 标签,标签和所有标签。我尝试了下面的代码,但它不起作用。
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id.next().next());
如何完全交换两个 div 标签。
【问题讨论】:
标签:
javascript
jquery
jquery-ui
【解决方案1】:
您的代码中有一些括号不匹配,看起来您可能正在尝试这样做:
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);
【解决方案2】:
你不能这样做,因为你不能连接一个字符串和一个 jQuery 对象。
试试这个:
var div = $('#AllBlock-'+Id);
div.insertAfter(div.next().next());
【解决方案3】:
应该是这样的
你应该在Id之后关闭括号,
jQuery('#AllBlock-'+Id).insertAfter('#AllBlock-'+Id).next().next());
【解决方案4】:
您需要先分离现有的 dom 对象,然后再重新使用它:
$('#divid').detach().insertAfter('#someotherdivid');
【解决方案5】:
我的理解是你想在点击最后一个 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/