如何使用jquery将每个输入和标签包装在一个div中

时间:2017-10-03 07:38:53

标签: jquery html

这是我的代码,我希望将每个输入和标签用div包围起来



<div>
    <input type="checkbox" name="checkbox1">
    <label for="checkbox1">checkbox1</label>
    <input type="checkbox" name="checkbox2">
    <label for="checkbox2">checkbox2</label>
    <input type="checkbox" name="checkbox3">
    <label div="checkbox3">checkbox3</label>
    <input type="checkbox" name="checkbox4">
    <label for="checkbox4">checkbox4</label>
</div>
&#13;
&#13;
&#13;

并且,我想用div包含每个输入和标签,如

&#13;
&#13;
<div>
  <div>
    <input type="checkbox" name="checkbox1">
    <label for="checkbox1">checkbox1</label>
  </div>
  <div>
    <input type="checkbox" name="checkbox2">
    <label for="checkbox2">checkbox2</label>
  </div>
  <div>
    <input type="checkbox" name="checkbox3">
    <label div="checkbox3">checkbox3</label>
  </div>
  <div>
    <input type="checkbox" name="checkbox4">
    <label for="checkbox4">checkbox4</label>
  </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:5)

试试这个

$('input').each(function() {
  $(this).next('label').andSelf().wrapAll('<div class="testing"/>');
});
.testing {
  background-color: blue;
}

.testing>label {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" name="checkbox1">
  <label for="checkbox1">checkbox1</label>
  <input type="checkbox" name="checkbox2">
  <label for="checkbox2">checkbox2</label>
  <input type="checkbox" name="checkbox3">
  <label div="checkbox3">checkbox3</label>
  <input type="checkbox" name="checkbox4">
  <label for="checkbox4">checkbox4</label>
</div>

答案 1 :(得分:1)

您可以使用$('input').map(function(index){ $(this).next().andSelf().wrapAll('<div>'); });

$('input').map(function(index){
  $(this).next().andSelf().wrapAll('<div>');
});

<强>演示

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <input type="checkbox" name="checkbox1">
    <label for="checkbox1">checkbox1</label>
    <input type="checkbox" name="checkbox2">
    <label for="checkbox2">checkbox2</label>
    <input type="checkbox" name="checkbox3">
    <label div="checkbox3">checkbox3</label>
    <input type="checkbox" name="checkbox4">
    <label for="checkbox4">checkbox4</label>
</div>
rowlist = []
c.execute("SELECT {rowid} from {whichTable}".\
          format (rowid = "rowid", whichTable = whichTable))
rowlist = c.fetchall ()
rowlistcount = len(rowlist)
print (rowlistcount)

答案 2 :(得分:1)

inputlabelmap相关联,然后选择两个特定元素并wrap

$('input').map(function() {
  $(this).next().andSelf().wrapAll('<div>');
});

JsFiddle