使用包装程序类在特定div中包装每2个差值元素

问题描述 投票:0回答:1

我正在尝试使用自定义div包装每两个元素。这是我的代码:

<div class="variation-radios">
    <input type="radio" name="attribute_pa" value="60-cm">
    <label for="60-cm">60 cm</label>
    <input type="radio" name="attribute_pa" value="70-cm">
    <label for="70-cm">70 cm</label>
    <input type="radio" name="attribute_pa" value="80-cm">
    <label for="80-cm">80 cm</label>
    <input type="radio" name="attribute_pa" value="90-cm">
    <label for="90-cm">90 cm</label>
</div>

我想去得到:

<div class="variation-radios">
    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="60-cm">
        <label for="60-cm">60 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="70-cm">
        <label for="70-cm">70 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="80-cm">
        <label for="80-cm">80 cm</label>
    </div>

    <div class="wrapper">
        <input type="radio" name="attribute_pa" value="90-cm">
        <label for="90-cm">90 cm</label>
    </div>      
</div>

问题是,这是两个不同的元素labelinput,我无法在其中添加一个类。如果只有输入,我可以使用jQuery wrapAll。但是我不知道如何用jQuery完全包装两个不同的html元素。

javascript jquery html jquery-plugins wrapall
1个回答
2
投票
此代码就像冠军一样:

<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <div class="variation-radios"> <input id="60-cm" type="radio" name="attribute_pa" value="60-cm"> <label for="60-cm">60 cm</label> <input id="70-cm" type="radio" name="attribute_pa" value="70-cm"> <label for="70-cm">70 cm</label> <input id="80-cm" type="radio" name="attribute_pa" value="80-cm"> <label for="80-cm">80 cm</label> <input id="90-cm" type="radio" name="attribute_pa" value="90-cm"> <label for="90-cm">90 cm</label> </div> <script> $('input').each(function() { $(this).add($(this).next('label')).wrapAll('<div class="wrapper"></div>') }); </script>

[它使用.each方法循环遍历每个input元素,然后向其添加下一个元素:label,然后调用.wrapAll将它们与div元素包装在一起。    
© www.soinside.com 2019 - 2024. All rights reserved.