edt*_*edt 0 jquery css-selectors wrapall
我正在开发一个下拉菜单,需要使用JQuery改变现有的html标记,使其适合设计.
这是一个简化的例子:在div中包含所有"ul",其中包含多个"li"(在同一个div中,每个UL不包含一个div).
<ul>
<li>foo</li>
</ul>
<ul>
<li>foo</li>
<li>foo</li>
</ul>
<ul>
<li>foo</li>
<li>foo</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
my_selection = [];
i = 0;
// find all ul's that have more than one li
$("ul").each(function(){
if($(this).find("li").length > 1){
// add this to my_selection
my_selection[i] = $(this);
i++;
} // if
}); // each
// wrap my_selection in div tags
$(my_selection).wrapAll(document.createElement("div"));
</script>
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了这个firebug错误:
"节点无法插入层次结构中的指定点"代码:"3"
我怎样才能使它工作?
这将是一个更清洁的方法:
$('ul:has(li)').wrap('<div></div>');
Run Code Online (Sandbox Code Playgroud)
首先,您不需要创建节点,只需将包装字符串提供给jQuery.其次,:has在此实例中使用选择器来减少each示例中的功能.最后,(这取决于您的预期功能)您可能想要使用wrap而不是wrapAll.
编辑:另一种选择是从相反的方式接近它.获取<li>标签然后抓住<ul>父母:
$('li:not(:only-child)').parent().filter('ul').wrap('<div></div>');
Run Code Online (Sandbox Code Playgroud)