代码之家  ›  专栏  ›  技术社区  ›  CMPalmer

如何使用jQuery插入一个围绕可变数量的子元素的<DIV>?

  •  3
  • CMPalmer  · 技术社区  · 17 年前

    我有如下类似的ASP.Net代码(这是在一个字段集中):

    <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。我还知道如何在选择后插入内容。

    我搞不懂的是(至少在深夜)如何在列表项中找到第一个标签之后的所有内容(或者基本上列表项中除第一个标签之外的所有内容都是另一种放置方式),并在document ready函数中围绕该内容加上一个DIV。

    更新:

    $('this')
    $("li label:first-child")
    以便仅选择列表项后出现的第一个标签。

    $(document).ready(function() {
    
        $('li label:first-child').each(function() {
            $(this).siblings().wrapAll('<div class="GroupThese"></div>');
        });
    });
    
    2 回复  |  直到 17 年前
        1
  •  5
  •   Owen Ryan Doherty    17 年前

    编辑 :更正的代码(有关更多信息,请参阅修订历史记录中的旧代码和注释)

    好的,这应该可以:

    $('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>
    
        2
  •  3
  •   Matt    17 年前

    var $div = $('li').wrapInner('<div></div>').children('div');
    $div.children('label').prependTo($div.parent());