简体   繁体   English

如何在jQuery中移动HTML元素?

[英]How do I move an HTML element in jQuery?

My HTML structure is like this: 我的HTML结构是这样的:

<div id="parent">
   <div id="1">Some content</div>
   <div id="2">Some content</div>
</div>

I want to move the element id="2" to place before id="1" so its will be like this: 我想将元素id="2"移到id="1"所以它将是这样的:

<div id="parent">
   <div id="2">Some content</div>
   <div id="1">Some content</div>
</div>

How do I do something like that in jQuery? 我如何在jQuery中做类似的事情?

You can use .insertBefore() , like this: 您可以使用.insertBefore() ,如下所示:

$("#2").insertBefore("#1");

Or, .prependTo() , like this: 或者, .prependTo() ,如下所示:

$("#2").prependTo("#parent");

...or the reverse using #1 and .insertAfter() and .appendTo() ...or several other ways actually, it just depends what you're actually after, the above 2 methods should be about the shortest possible though, given 2 IDs. ...或反过来使用#1.insertAfter().appendTo() ...或实际上其他几种方式,它只取决于你实际使用的内容,上述两种方法应该是最短的,但是,给出2个ID。

I'm assuming this is just an example, remember to use IDs that don't start with a number in an actual HTML4 page, they're invalid and cause several issues. 假设这只是一个例子,记得使用不以实际HTML4页面中的数字开头的ID,它们无效并导致一些问题。

简单地说:

$('#1').before($('#2'));

有没有想过使用jQuery UI Sortable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM