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

5
这是我的代码,我希望用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>

我希望您能将每个输入框和标签用

标签包裹起来,例如:

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


2
你为什么要这样做?你现有的代码有什么问题? - Michael Hancock
你有什么问题? - Kevin Kloet
实际上,我无法解释我的问题,但我想使用jQuery将每个输入和标签放在div中。 - Ashok Khot
3个回答

7

Try this

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


谢谢@影魔,它有效。 - Ashok Khot

1
你可以使用 .map()
$('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>


1
inputlabel 都与 map 相关联,选择这两个特定元素并将它们 包装 起来:
$('input').map(function() {
  $(this).next().addBack().wrapAll('<div>');
});

JsFiddle

由于 .addSelf() 已被弃用,因此更新为使用 .addBack()


1
andSelf() 已在 jQuery 3.0 中被移除;请使用 .addBack() 替代,两者的功能应该是相同的。 - smolo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接