如何使用jQuery插入< DIV>缠绕可变数量的子元素?
题
我有类似于以下的ASP.Net代码(这是在FIELDSET中):
<ol>
<li>
<label>Some label</label>
<one or more form controls, ASP.Net controls, labels, etc.>
</li>
<li>
<label>Another label</label>
<... more of the same...>
</li>
...
</ol>
我试图保持我的标记尽可能干净,但我已经决定,出于各种原因,我需要在第一个标签之后将DIV包装在列表项中的所有内容中,如下所示:
<ol>
<li>
<label>Some label</label>
<div class="GroupThese">
<one or more form controls, ASP.Net controls, labels, etc.>
</div>
</li>
<li>
<label>Another label</label>
<div class="GroupThese">
<... more of the same...>
</div>
</li>
...
</ol>
我宁愿用“不引人注目的Javascript”来做这件事。通过jQuery而不是用额外的标记乱丢我的页面,所以我可以在语义上保持表单“干净”。
我知道如何编写一个jQuery选择器来获取每个列表项$(&quot; li + label&quot;)中的第一个标签,或者使用:first-child。我也知道在选择之后如何插入东西。
我无法弄清楚(至少在深夜)是如何在列表项中的第一个标签之后找到所有内容(或者除了第一个标签之外,列表项中的所有内容基本上都是另一种放置方式它)并在文档就绪函数中围绕它包装DIV。
<强>更新强>
一旦我从周围删除了单引号,Owen的代码就可以工作了:
$('this')并设置正确的decendent选择器:
$("li label:first-child"),以便只选择列表项后面的第一个标签。
这是我做的:
$(document).ready(function() {
$('li label:first-child').each(function() {
$(this).siblings().wrapAll('<div class="GroupThese"></div>');
});
});
解决方案
修改:更正后的代码(有关详细信息,请参阅修订历史记录和评论中的旧代码)
好的,这应该有效:
$('li label:first-child').each(function() {
$(this).siblings().wrapAll('<div class="li-non-label-child-wrapper">');
});
从:
<li>
<label>Some label</label>
<div>stuff</div>
<div>other stuff</div>
</li>
<li>
<label>Another label</label>
<div>stuff3</div>
</li>
产生
<li>
<label>Some label</label>
<div class="li-non-label-child-wrapper">
<div>stuff</div>
<div>other stuff</div>
</div>
</li>
<li>
<label>Another label</label>
<div class="li-non-label-child-wrapper">
<div>stuff3</div>
</div>
</li>
其他提示
一种方法是将所有内容包装在&lt; li&gt;内。然后移出标签,例如
var $div = $('li').wrapInner('<div></div>').children('div');
$div.children('label').prependTo($div.parent());
不隶属于 StackOverflow