asp.net - 我如何使用 jQuery 插入一个 <DIV> 包裹在可变数量的子元素周围?

标签 asp.net jquery css forms

我有类似于以下的 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>

我宁愿通过 jQuery 使用“不显眼的 Javascript”来做到这一点,而不是用额外的标记在我的页面上乱扔垃圾,这样我就可以保持表单在语义上“干净”。

我知道如何编写一个 jQuery 选择器来获取每个列表项中的第一个标签 $("li+label") 或使用 :first-child。我也知道如何在选择后插入东西。

我无法弄清楚(至少在这个深夜)是如何找到列表项中第一个标签之后的所有内容(或者基本上列表项中除了第一个标签之外的所有内容都是另一种放置方式它)并在文档就绪函数中围绕它包装一个 DIV。

更新:

一旦我从周围删除了单引号,Owen 的代码就可以工作了:

$('this')
and set the proper decendent selector:
$("li label:first-child")
in order to only select the first label that occurs after a list item.

Here is what I did:

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

关于asp.net - 我如何使用 jQuery 插入一个 <DIV> 包裹在可变数量的子元素周围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/211137/

相关文章:

asp.net - 使用标准字段获取用户的个人资料值列表,例如电子邮件

asp.net - System.Web.Configuration.MachineKeySection.GetDecodedData中的 "Unable to validate data"异常表示什么

c# - HttpCacheability.NoCache 和 Response.CacheControl = "no-cache"之间有什么不同?

jquery - 将 Twitter Bootstrap 从 940px fixed 更改为 960px fixed 有什么缺点吗?

html - 整页背景的良好图像尺寸是多少

jquery - 菜单悬停效果在 IE 中不起作用

php - Chrome 的滚动延迟

html - 如何使网站图像和幻灯片看起来像是设备屏幕?

javascript - 在 jQuery 中使用 setInterval 和数组更改多个元素的背景颜色

javascript - 计算没有显示的 div 中可见 li 项目的数量