jQuery-使用wrap()包装多个元素? [英] jQuery - use wrap() to wrap multiple elements?

查看:195
本文介绍了jQuery-使用wrap()包装多个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何使用wrap()<div>中包装多个元素(具有不同的类)?

How would I go about using wrap() to wrap multiple elements (with different classes) inside a <div>?

例如,在我正在使用的表单上,有一大堆复选框输入和标签,形式为:

For example, on the form I'm working on there is a big list of checkbox inputs and labels in the form of:

<input>
<label>
<input>
<label>

我想在输入和标签周围包裹一个<div>,所以结果将是:

I'm wanting to wrap a <div> around the input and label, so the result would be:

<div>
  <input>
  <label>
</div>
<div>
  <input>
  <label>
</div>

谢谢!

推荐答案

您可以使用.wrapAll()方法.

$('form > input').each(function(){
    $(this).next('label').andSelf().wrapAll('<div class="test"/>');
});

如果您的标记始终具有完全相同的顺序,我更愿意使用:

If your markup has always the exact same order, I'd prefer to use:

var $set = $('form').children();    
for(var i=0, len = $set.length; i < len; i+=2){
    $set.slice(i, i+2).wrapAll('<div class="test"/>');
}    

应该更快.

参考: .wrapAll() .slice()

这篇关于jQuery-使用wrap()包装多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆