jquery在子ul-tag之前将html插入到列表中 [英] jquery insert html into list before a child ul-tag

查看:109
本文介绍了jquery在子ul-tag之前将html插入到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

  <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,但是能够在正确的位置插入。

after the 3 in the list. I have played with .append and .prepend but witout beeing able to insert at the right place.

任何帮助都将不胜感激

Br。 Anders

Br. Anders

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

There is a correct answer below. If you use that then it will run through only one level. But same example is is capable of running through multible levels. Just change ('>li>ul') to ('ul') and all nested ul's will be found and handled. Perfect!

(将通过无尽的嵌套ul级别运行)

(will run through endless levels of nested ul's)

$('#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>


推荐答案

这对你有用;

// 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());
});

这篇关于jquery在子ul-tag之前将html插入到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆