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
How do I move an HTML element in jQuery?
提问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 #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
and.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?