Javascript 如何在 jQuery 中移动 HTML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4428312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:22:32  来源:igfitidea点击:

How do I move an HTML element in jQuery?

javascriptjqueryhtmldom

提问by GusDeCooL

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 中做类似的事情?

回答by Nick Craver

You can use .insertBefore(), like this:

你可以使用.insertBefore(),像这样:

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

Or, .prependTo(), like this:

或者.prependTo(),像这样:

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

...or the reverse using #1and .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.

...或相反使用#1and.insertAfter().appendTo()...或其他几种方式实际上,这仅取决于您实际追求的内容,尽管给定 2 个 ID,上述 2 种方法应该是尽可能最短的方法。

I'm assumingthis 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,它们是无效的并会导致几个问题。

回答by David Tang

Simply do:

简单地做:

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

回答by Pit

Ever thought about using jQuery UI Sortable?

有没有想过使用jQuery UI Sortable