简体   繁体   English

将具有特定类的li元素移入和div

[英]Move li elements with certain class into and div

I am trying to use the .append function in jquery. 我正在尝试在jquery中使用.append函数。 I have a div with li elements in it. 我有一个包含li元素的div。 They have different classes, lets say odds and evens. 他们有不同的类别,可以说是偶数。 I would like the li's with the class "odd" moved into another div with li's in it. 我想将具有“ odd”类的li移到另一个包含li的div中。 How can I do this? 我怎样才能做到这一点? Here is my setup: Edit . 这是我的设置: 编辑 This was in valid markup, I just didn't put all in. Fixed now for others. 这是有效的标记,我只是没有全部投入。现在为其他人修复。

<div id="col1">
    <ul>
    <li class="odd"></li>
    <li class="even"></li>
    <li class="odd"></li>
    <li class="even"></li></ul>
</div>
<div id="col2">
<ul>
<li></li>
</ul>
</div>

So then the output is: 因此,输出为:

<div id="col1">
    <li class="even"></li>
    <li class="even"></li>
    <li class="even"></li>
    <li class="even"></li>
</div>
<div id="col2">
    <li class="odd"></li>
    <li class="odd"></li>
    <li class="odd"></li>
    <li class="odd"></li>
</div>

If you already have <div> elements which you are moving elements into you can try this: 如果已经有将元素移入的<div>元素,则可以尝试以下操作:

$("#col1 li").each(function(){
    var $li = $(this);
    if ($li.hasClass("odd")) $("#odd").append($li);
    if ($li.hasClass("even")) $("#even").append($li);
});

working example: 工作示例:

http://jsfiddle.net/hunter/jq8bW/ http://jsfiddle.net/hunter/jq8bW/

Your <li> must be contained inside a list <ol> or <ul> . 您的<li>必须包含在列表<ol><ul>

First, append <div id="col2"> , but that div must also contain a <ul> or <ol> to be valid. 首先,附加<div id="col2"> ,但是该div还必须包含<ul><ol>才有效。 Then append the odd <li> to the new list. 然后将奇数<li>附加到新列表。

// Create <div id='col2'><ul id='col2-list'></ul></div>
$("#col1").after("<div id='col2'><ul id='col2-list'></ul></div>");

// Place the list elements inside it.
$("li.odd").appendTo($("#col2-list"));

Let's say you have valid html structure like this one: 假设您具有这样的有效html结构:

<ul id="col1">
    <li class="even"></li>
    <li class="odd"></li>
    <li class="odd"></li>
    <li class="even"></li>
</ul>
<ul id="col2">
</ul>

Here the jQuery code: 这里是jQuery代码:

$('#col1 > .odd').each(function() {
    $(this).detach().appendTo('#col2');
});

Edit: the use of .detach() is not mandatory. 编辑: .detach()的使用不是强制性的。

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

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