0

我有这样的事情:

<li>
  <a></a>
  "(1)"
  <ul></ul>
</li>

我希望它最终是这样的:

<li>
  <span>
    <a></a>
    "(1)"
  </span>
  <ul></ul>
</li>

如何做到这一点?

4

4 回答 4

1
$ul = $('li ul');
$('li ul').remove();
$('li').wrapInner('<span>');
$('li').append($ul);

作品。请参阅http://jsfiddle.net/Lhg32/(感谢您的评论!)

于 2012-12-07T06:29:13.870 回答
1
var content = $('li').clone(true),
         ul = content.children('ul').remove();

$('li').html($('<span />').append(content.contents()).append(ul));

小提琴

于 2012-12-07T06:45:32.050 回答
0

http://jsfiddle.net/lamarant/XjQek/

HTML

<ul>
    <li>This is Item 1
        <ul>
            <li>Item 1 Sub 1</li>
            <li>Item 1 Sub 2</li>
            <li>Item 1 Sub 3</li>
        </ul>
    </li>
    <li>This is Item 2
        <ul>
            <li>Item 2 Sub 1</li>
            <li>Item 2 Sub 2</li>
            <li>Item 2 Sub 3</li>
            <li>Item 2 Sub 4</li>
        </ul>
    </li>
</ul>

Javascript

$('ul li').not('ul ul li').each(function () {
        var $clone = $(this).clone(true);
        var $origUL = $('ul', $(this)).first();
        var $newUL = $('<ul></ul>');
        $newUL.html($origUL.html());
        $clone.children('ul').remove();
        $(this).html('').append($('<span>' + $clone.html().trim() + '</span>')).append($newUL);
    });

结果

<ul>
    <li><span>This is Item 1</span>
        <ul>
            <li>Item 1 Sub 1</li>
            <li>Item 1 Sub 2</li>
            <li>Item 1 Sub 3</li>
        </ul>
    </li>
    <li><span>This is Item 2</span>
        <ul>
            <li>Item 2 Sub 1</li>
            <li>Item 2 Sub 2</li>
            <li>Item 2 Sub 3</li>
            <li>Item 2 Sub 4</li>
        </ul>
    </li>
</ul>
于 2013-05-03T18:49:58.730 回答
-3

尝试这个

$('li a').before('&lt;span&gt;');
$('li ul').before('&lt;/span&gt;');

希望这可以帮助!

于 2012-12-07T06:27:21.937 回答