我有这个:
<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但是能够在正确的位置插入。
任何帮助将不胜感激
溴。安德斯
下面有一个正确的答案。如果您使用它,那么它将只运行一个级别。但同样的例子是能够运行多个级别。只需将('&gt; li&gt; 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>
答案 0 :(得分: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());
});
答案 1 :(得分: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>
答案 2 :(得分:1)
last-child 选择器将确保您在其后添加新项目。
您可以将其用作
$('<li class="new_ul">4</li>').appendTo("ul#pick_me > li:last-child");
答案 3 :(得分:0)
使用.html(),它将为您提供内部文本。操纵字符串。然后使用.html(newHtml)设置新的内部文本。
prepend和append的问题在于你不需要前置或附加,你需要在中间插入(在3之后)。