簡體   English   中英

使用包裝器 class 將每 2 個不同的元素包裝在特定的 div 中

[英]Wrap every 2 differents elements inside specific div with wrapper class

我正在嘗試用我的自定義 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>

我希望 go 得到:

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

問題是 tehre 是兩個不同的元素labelinput ,我不能在那里添加 class。 如果只有輸入,我可以使用 jQuery wrapAll。 但我不知道如何用 jQuery 完全包裝兩個不同的 html 元素。

這段代碼就像一個冠軍:

<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 元素一起包裝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM