使用jQuery:使用.before()在另一个div中包装div

使用jQuery:使用.before()在另一个div中包装div,jquery,Jquery,我试图使用jQuery在以下代码周围添加一个div: <div class="fsSubField"> <input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip"> <br> <label class="fsSupporting" for="field1574450

我试图使用jQuery在以下代码周围添加一个div:

<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>


邮政编码
因此,最后我有:

<div class="fsSubFieldGroup" style="margin-top:5px;">
<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>
</div>


邮政编码
我尝试了以下方法:

$('input.fsFormatZipCA').parent().before('<div> class="fsSubFieldGroup" style="margin-top:5px;">');
$('input.fsFormatZipCA').parent().after('</div>');
<div class="fsSubFieldGroup" style="margin-top: 5px;"></div>
<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>
$('input.fsFormatZipCA').parent().before('class=“fsSubFieldGroup”style=“margin top:5px;”>);
(“”)之后的$('input.fsFormatZipCA').parent();
由于表单的动态特性,我需要能够根据“input.fsFormatZipCA”进行选择

我认为这是可行的,但问题是jQuery正在做以下工作:

$('input.fsFormatZipCA').parent().before('<div> class="fsSubFieldGroup" style="margin-top:5px;">');
$('input.fsFormatZipCA').parent().after('</div>');
<div class="fsSubFieldGroup" style="margin-top: 5px;"></div>
<div class="fsSubField">
<input id="field15744501-zip" class="fsField fsFieldZip fsFormatZipCA" type="text" value="" size="8" name="field15744501-zip">
<br>
<label class="fsSupporting" for="field15744501-zip">Postal Code</label>
</div>


邮政编码
您似乎在寻找
。包装

$('input.fsFormatZipCA').parent().wrap(
  $('<div>', {
    'class': 'fsSubFieldGroup',  // class is a reserved word
    css: {
      'margin-top': 5  // - is an invalid identifier character
    }
  })
);
$('input.fsFormatZipCA').parent().wrap('<div class="fsSubFieldGroup" style="margin-top:5px;">');
$('input.fsFormatZipCA').parent().wrap(
$('', {
'class':'fsSubFieldGroup',//class是保留字
css:{
“页边距顶部”:5/-是无效的标识符字符
}
})
);
.before
在元素之前插入元素。它不会通过简单地在HTML字符串前加前缀来构造HTML。

使用
.wrap()

$('input.fsFormatZipCA').parent().wrap(“”);
jQuery文档中的更多信息:


旁注:您可能注意到
.wrap()
函数为您添加了
。这让事情变得容易多了。

我建议:

$('.fsFormatZipCA').parent().wrap('<div class="fsSUbFieldGroup" />');
$('.fsFormatZipCA').parent().wrap('');
和的可能重复。
.before()
.after()
是DOM操作方法。它们用于插入DOM节点,在字符串连接或对源代码进行更改之前不会插入。