如何在jQuery中移动HTML元素? [英] How do I move an HTML element in jQuery?

查看:160
本文介绍了如何在jQuery中移动HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML结构如下:

My HTML structure is like this:

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

我想移动元素 id =2 id =1之前放置,所以它将如下所示:

I want to move the element id="2" to place before id="1" so its will be like this:

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

如何在jQuery中执行类似的操作?

How do I do something like that in jQuery?

推荐答案

您可以使用 .insertBefore( ) ,如下所示:

You can use .insertBefore(), like this:

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

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

Or, .prependTo(), like this:

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

...或反向使用#1 .insertAfter() .appendTo() ...或其他几种方式实际上,这只是取决于你以后的实际情况,上述2种方法应该是尽可能短的,但是给定2个ID。

...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.

我假设这只是一个例子,请记住使用不能在实际HTML4页面中以数字开头的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.

这篇关于如何在jQuery中移动HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆