jQuery - 使用 wrap() 来包装多个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3475594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:31:07  来源:igfitidea点击:

jQuery - use wrap() to wrap multiple elements?

jquery

提问by Probocop

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

我将如何使用wrap()将多个元素(具有不同的类)包装在一个<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>

etc

等等

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

我想环绕<div>输入和标签,所以结果是:

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

Thanks!

谢谢!

回答by jAndy

You can use the .wrapAll()method.

您可以使用该.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"/>');
}    

Should be significant faster.

应该明显更快。

Ref.: .wrapAll(), .andSelf(), .slice()

参考:.wrapAll(), .andSelf(), .slice()

回答by James

$('input+label').each(function(){
    $(this).prev().andSelf().wrapAll('<div>');
});?

回答by Lida

If you have something like this:

如果你有这样的事情:

<input id="input1">
<label id="label1">
<input id="input2">
<label id="label2">

Then you can use jQuery:

然后你可以使用jQuery:

 jQuery("#input1").next().andSelf().wrapAll('<div id="newDiv" />');
 jQuery("#input2").next().andSelf().wrapAll('<div id="newDiv" />');

and get this:

得到这个:

<div id="newDiv">
  <input id="input1">
  <label id="label1">
</div>
<div id="newDiv">
  <input id="input2">
  <label id="label2">
</div>

Worked for me :-)

为我工作:-)

回答by RaYell

jQuery function wrapAllallows you to wrap multiple elements but if you have a DOM like you wrote then it won't work too well as you can't easily match a part of label and input with a selector. I suggest adding some classes to each part and then using wrapAll.

jQuery 函数wrapAll允许你包装多个元素,但如果你有一个像你写的那样的 DOM,那么它就不会工作得很好,因为你不能很容易地将标签和输入的一部分与选择器匹配。我建议为每个部分添加一些类,然后使用 wrapAll。

<input class="i1"/>
<label class="i1"/>
<input class="i2"/>
<label class="i2"/>

$('.i1').wrapAll('<div/>');
$('.i2').wrapAll('<div/>');

This will give you

这会给你

<div>
    <input class="i1"/>
    <label class="i1"/>
</div>
<div>
    <input class="i2"/>
    <label class="i2"/>
<div>