3

将新的 li 元素插入嵌套集模型的特定位置的最佳方法是什么?

例如,以下列表:

<ol class="nested">
    <li id="list_1"></li>
    <li id="list_2">
        <ol>
            <li id="list_3"></li>
            <li id="list_4"></li>
        </ol>
    </li>
    <li id="list_5"></li>
</ol>

假设我想插入一个新的 li 作为 #list_2 的孩子,我可以这样做:

$('#list_'+parent_ID+' ol > li:last-child').after('<li id=""></li>');

但是如果 parent 将是 #list_1 或 #list_4 任何想法都行不通!?

4

5 回答 5

1

If I understood correctly, this example on jsfiddle might be what you are looking for?! If there already is an <ol> inside the parent element, the <li> is appended. If the parent <li> is empty, a new <ol> is created before the new child is appended to it.

function appendItemToList(parentId) {
    var $thelist = $("#list_"+parentId),
        $ol = $thelist.find("> ol");

    if(!$ol.length) {
        $ol = $("<ol />").appendTo($thelist);
    }
    $ol.append("<li id=''></li>");
}
于 2011-10-03T21:57:08.963 回答
1

Using iff plugin -

var parent_ID = 1;
$('#list_' + parent_ID).
    iff($(this).children('ol').length > 0)
    .append("<li>new</li>").end()
    .iff($(this).children('ol').length == 0)
    .append("<ol><li>new</li></ol>");

Demo - http://jsfiddle.net/MUcbW/2/

于 2011-10-03T21:57:36.563 回答
1

Here's an example, adding the appropriate elements on click:

$('ol.nested > li').bind('click', function(){
    var elem;
    if ($('ol', this).length > 0) {
        elem = $(this).find('ol');
    } else {
        elem = $('<ol>').appendTo($(this));
    }
    elem.append("<li>new</li>");
});
于 2011-10-03T21:59:00.923 回答
0

有很多方法。一个可能是这样的:

if ($('#list_'+parent_ID+' ol').length > 0) {
  $('#list_'+parent_ID+' ol > li:last-child').after('<li id=""></li>');
} else {
  $('#list_'+parent_ID).append('<ol><li id=""></li></ol>');
}

你可以在这里测试

于 2011-10-03T21:47:29.870 回答
0

您可以在一行中执行此操作,例如:

$('#list_' + parentId).contents().andSelf().filter('li').last().after('<li id=""></li>');

jsFiddle - http://jsfiddle.net/FloydPink/TSBKY/

于 2011-10-03T21:54:27.633 回答