拆除后如何在特定位置插入元素?

时间:2017-09-09 21:55:28

标签: jquery

当使用id engraving_txt_1输入时出现错误,这是html结构,但只有在验证表单时才会出现错误,如果用户从下拉列表中选择“是”,则会插入engraving_txt_1 input field当用户在该下拉菜单中选择否时删除。我使用此代码插入$(engraving_li).insertBefore("#divcount_1");,它会在我想要的位置正确插入,但当错误ID engraving_txt_1-error变得可见时,它会搞砸。无论是否有错误,如何正确插入?

<div id="li_engraving_txt_1" class="row" style="display: block;">
 <span class="type1 form-group col-md-2"><span class="left-label"><span id="red">*</span>Engraving Text:</span>
   XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
   <label id="engraving_txt_1-error" class="fieldError" for="engraving_txt_1">This field is required.</label>
   <label style="margin-left:25%;" id="divcount_1"></label>
   <input type="hidden" id="label_1" name="labelCount[]" class="element text form-control" value="">
 </span>
 <span class="type1 form-group col-md-2"><span class="left-label"><span id="red">*</span>Engraving Font:</span>
   <select class="element select form-control" id="engraving_font_1" name="cb_engraving_font[]">
     <option value="Cherokee Font">Cherokee Font</option>
     <option value="Narkism Font">Narkism Font</option>
     <option value="Segoe Script Font">Segoe Script Font</option>
   </select>
 </span>
</div>

1 个答案:

答案 0 :(得分:1)

我们必须尽可能具体,不要针对不需要的DOM元素。

&#13;
&#13;
$('#li_engraving_txt_1')
    .find('.type1.form-group.col-md-2')
        .first()
            .find('.left-label')
                .after('.......HIT........')
&#13;
<div id="li_engraving_txt_1" class="row" style="display: block;">
 <span class="type1 form-group col-md-2"><span class="left-label"><span id="red">*</span>Engraving Text:</span>
   XXXXXXXXXXXXXXX
   <label id="engraving_txt_1-error" class="fieldError" for="engraving_txt_1">This field is required.</label>
   <label style="margin-left:25%;" id="divcount_1"></label>
   <input type="hidden" id="label_1" name="labelCount[]" class="element text form-control" value="">
 </span>
 <span class="type1 form-group col-md-2"><span class="left-label"><span id="red">*</span>Engraving Font:</span>
   <select class="element select form-control" id="engraving_font_1" name="cb_engraving_font[]">
     <option value="Cherokee Font">Cherokee Font</option>
     <option value="Narkism Font">Narkism Font</option>
     <option value="Segoe Script Font">Segoe Script Font</option>
   </select>
 </span>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;