3

我有这个:

  <ul id="pickme">
    <li>1</li>
    <li>2</li>
    <li>3
      <ul>
        <li>3-1</li>
      </ul>
    </li>
  </ul>

但是想要这个:

  <ul id="pickme">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li class="new_ul">
      <ul>
        <li>3-1</li>
      </ul>
    </li>
  </ul>

换句话说,我需要插入

</li><li class="new_ul">

在列表中的 3 之后。我玩过 .append 和 .prepend 但无法在正确的位置插入。

任何帮助,将不胜感激

兄弟。安德斯


下面有正确答案。如果你使用它,那么它将只运行一个级别。但同样的例子是能够通过多个层次运行。只需将 ('>li>ul') 更改为 ('ul') 即可找到并处理所有嵌套的 ul。完美的!

(将贯穿无尽的嵌套 ul 级别)

$('#pickme').find('ul').each(function() {
    $(this).wrap('<li class="new_ul"></li>').parent().insertAfter($(this).parent().parent());
});

在这种情况下:

  <ul id="pickme">
    <li>1</li>
    <li>2</li>
    <li>3
      <ul>
        <li>3-1
          <ul>
            <li>3-1-1</li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>

将会:

  <ul id="pickme">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li class="new_ul">  <<new li
      <ul>
        <li>3-1</li>
        <li class="new_ul">  <<new li
          <ul>
            <li>3-1-1</li>
          </ul>
        </li>
      </ul>
    </li>
    </li>
  </ul>
4

4 回答 4

3

这对你有用;

// get the #pickme element
var pickme = $('#pickme');

// find all the LI elements that are directly under #pickme
var pickmeLIs = pickme.find('>li');

// find all the UL elements that are directly under our found LI elements
var pickmeULs = pickmeLIs.find('>ul');

// loop through our UL elements
pickmeULs.each(function() {

    // wrap this UL element in the new LI element
    $(this).wrap('<li class="new_ul"></li>');

    // select the wrapping LI we just added to the UL element
    var wrapingLI = $(this).parent();

    // find our original parent LI element
    var originalParent = $(this).parent().parent();

    // move this and the new wrapping LI to the right place
    wrapingLI.insertAfter(originalParent);
});

这可以浓缩为;

$('#pickme').find('>li >ul').each(function() {
    $(this).wrap('<li class="new_ul"></li>').parent().insertAfter($(this).parent().parent());
});
于 2009-11-05T13:23:15.293 回答
2

如果您有办法知道有多少列表项#pickme可以使用$('#pickeme li:eq(theIndex)'),请使用以下方法:

$('#pickme li:last').after('<li class="new_ul"><ul><li>3-1</li></ul></li>');

测试和工作。

更新

多亏了 bobince 和 Myra,我现在有了以下内容,可以满足您的要求:

$('#pickme li:last-child').replaceWith('<li class="new_ul"><ul><li>3-1</li></ul></li>');

输出:

<ul id="pickme">
    <li>1</li>
    <li>2</li>
    <li class="new_ul">
      <ul>
        <li>3-1</li>
      </ul>
    </li>
</ul>
于 2009-11-05T13:34:49.077 回答
1

last-child选择器将确保您在其后添加新项目。

您可以将其用作

$('<li class="new_ul">4</li>').appendTo("ul#pick_me > li:last-child");

于 2009-11-05T13:26:13.563 回答
0

使用 .html(),它将为您提供内部文本。操作字符串。然后使用 .html(newHtml) 设置新的内部文本。

您对 prepend 和 append 的问题是您不需要 prepend 或 append,您需要在中间插入(在 3 之后)。

于 2009-11-05T13:15:05.047 回答