javascript - jQuery concat 变量输入名称未更新

标签 javascript jquery html

在“单击添加另一个”事件中,此变量跟踪动态生成的元素的索引:

var index = $(this).parent().parent().parent().parent().index();

它工作正常,通过控制台日志记录可以证明。 index 变量的最小值为 1,没有最大值。我创建原始 html 片段的副本并将其附加在下面,并替换输入名称(以便我可以运行 jQuery 验证):

$("[name=officeAddressLine1]:last").replaceWith("<input type='text' data-
id='"+index+"' class='otherBusinessField' id='officeAddressLine"+index+"'
name='officeAddressLine"+index+"'>");

我连接 index 的值以使输入唯一,对于第一个动态生成的元素,我得到 officeAddressLine2 (这是正确的),但之后的所有元素继续连接 2,而不是 3、4、5...

我始终能够在点击事件上记录 index 的正确值。为什么这个值在输入标记内部时不会更新?

这是 jQuery 事件处理程序:

$('#BusinessBox').on('click', '.otherOffices [value=y]', function() {
    if ($(this).parent().parent().parent().parent().next().attr('name') == 'otherOffice'){
        return false;
    }
    var index = $(this).parent().parent().parent().parent().index();
    var template = $(this).parent().parent().parent().parent().html().replace(/name="otherOfficeRadio\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/id="otherOfficeRadioYes\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/id="emailProcessedByMe\d+"/g, function(str) {
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="emailProcessedByMe\d+"/g, function(str) {
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });

    template = template.replace(/id="emailProcessedByStaff\d+"/g, function(str) {
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="emailProcessedByStaff\d+"/g, function(str) {
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });


    template = template.replace(/id="weelChairAccessible\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="weelChairAccessible\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/id="twoBlocksFromPublicTransport\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="twoBlocksFromPublicTransport\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });


    template = template.replace(/id="otherOfficeRadioNo\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="otherOfficeRadioNo\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    template = template.replace(/for="otherOfficeRadioYes\d+"/g, function(str) {
        //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', str).remove();
        return str.replace(/\d+/g, function(n) {
            return ++n;
        });
    });
    // console.log(template);
    //$('.chosen-container.chosen-container-single.chosen-container-single-nosearch', template).remove();
    $('[name=otherOffice]:last').after($('<div name="otherOffice" class="yellow_sec textBlock">' + template.replace(/style=".*?"/g, '').replace(/Primary/g, 'Additional').replace(/(Additional\s\w+)\s\d*/g, '$1 ' + index + ' ') + '</div>').hide().fadeIn());

    console.log(index, "INDEX");
    //BEGIN change input names for other business location for validation
    $("[name=officeAddressLine1]:last").replaceWith("<input type='text' data-id='"+index+"' class='otherBusinessField' id='officeAddressLine"+index+"' name='officeAddressLine"+index+"'>");
    $("[name=city]:last").replaceWith("<input type='text' class='otherBusinessField' data-id='"+index+"' id='city"+index+"' name='city"+index+"'>");
    $("[name=zip]:last").replaceWith("<input type='text' class='otherBusinessField' data-id='"+index+"' id='zip"+index+"' name='zip"+index+"'>");
    $("[name=stateOrProvince]:last").attr('name', 'stateOrProvince'+index).addClass('otherBusinessField');
    $("[name=officePhone]:last").replaceWith("<input class='otherBusinessField' type='text' data-id='"+index+"' id='officePhone"+index+"' name='officePhone"+index+"'>");
    $("[name=takesCallsStart]:last").attr('name', 'takesCallsStart' + index).addClass('otherBusinessField');
    $("[name=takesCallesEnd]:last").attr('name', 'takesCallesEnd' + index).addClass('otherBusinessField');
    $("[name=otherOffice]:last").find('.bootstrap-switch:last').replaceWith("<input type='checkbox' class='otherBusinessField' data-id='"+index+"' id='takesCallsStartSuffix"+index+"' name='takesCallsStartSuffix"+index+"'>");
    $("[name=otherOffice]:last").find('.bootstrap-switch:first').replaceWith("<input type='checkbox' class='otherBusinessField' data-id='"+index+"' id='takesCallsEndSuffix"+index+"' name='takesCallsEndSuffix"+index+"'>");

    $("[name=businessEmail]:last").replaceWith("<input type='text' data-id='"+index+"' id='businessEmail"+index+"' name='businessEmail2'>");
    $("[name=emailProcessedByMe]:last").replaceWith("<input type='checkbox' data-id='"+index+"' id='emailProcessedByMe"+index+"' name='emailProcessedByMe2'>");
    $("[name=emailProcessedByStaff]:last").replaceWith("<input type='checkbox' data-id='"+index+"' id='emailProcessedByStaff"+index+"' name='emailProcessedByStaff2'>");
    $("[name=emailRespondedBy]:last").replaceWith("<select id='emailRespondedBy"+index+"' name='emailRespondedBy2'>");
    //END change input names for other business location for validation

    $("#takesCallsStartSuffix"+index).bootstrapSwitch({onText:"AM", offText: "PM",onSwitchChange:takesCallsEvent});
    $("#takesCallsEndSuffix"+index).bootstrapSwitch({onText:"AM", offText: "PM", state:true, onSwitchChange:takesCallsEvent});
    $("[name=otherOffice]:last").find('.chosen-container').remove();
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        $('input').placeholder();
    }
    $('.zip').mask('99999-ZZZZ', {translation: {'Z': {pattern: /[0-9]/, optional: true}}});
    /*$(".takesCallsStart").chosen({disable_search_threshold: 12});
    $(".takesCallsEnd").chosen({disable_search_threshold: 12});
    $(".takesCallsStartSuffix").chosen({disable_search_threshold: 10});
    $(".takesCallsEndSuffix").chosen({disable_search_threshold: 10});
    */
    updateStateOrProvinceList("", index-1, "");
    $("[name=stateOrProvince]:last").chosen({width: '100%'});
    $(".chosen-container.chosen-container-single").on("focusout", function() {
        $(this).parent().find(".takesCallsStart").blur();
        $(this).parent().find(".takesCallsEnd").blur();
        $(this).parent().find(".takesCallsStartSuffix").blur();
        $(this).parent().find(".takesCallsEndSuffix").blur();
        $(this).parent().find("[name=stateOrProvince]").blur();
    });

});

相关 HTML 的开头和相关部分 - 在最后一个单选按钮上选择"is"会创建其上方模板的新副本:

                        <div id="BusinessBox" class="accordion_in">
                      <div class="acc_head">Business & Licensing
                        <div id="businessStatus" class="tabStatus"></div> 

                      </div>
                        <div class="acc_content">           
                            <div class="main_form_sec">             
                                <div class="main_formInr">
                                    <h3>Business and Licensing</h3>
                                    <h6><span>*</span> Required Information</h6>
                                    <div name="otherOffice">
                                    <h5>Office and Contact Information</h5>

                                    <div class="form_row">
                                        <label>Primary Practice Company Name or DBA</label>
                                        <ul class="form_colom_list">                            
                                            <li>
                                                <input name="companyName" placeholder="Your practice name here" type="text" class="big"/>
                                            </li>                           
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list">                            
                                            <li>
                                                <label><span>*</span>Primary Office Street Address (Line 1)</label><input name="officeAddressLine1" id='officeAddressLine1' type="text" class="big_sml"/>
                                            </li>
                                            <li>
                                                <label>Primary Office Street Address (Line 2) (Optional)</label><input name="officeAddressLine2" type="text" class="big_sml"/>
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="form_row">
                                        <ul class="form_colom_list">                            
                                            <li>
                                                <label><span>*</span>City</label><input id="city" name="city" type="text">
                                            </li>
                                            <li>
                                                <label><span>*</span>State/Territory/Province</label>
                                                <select name="stateOrProvince" id="stateOrProvince" class="select_list big selectBox">
                                                    <option>select</option>
                                                    <option>select</option>
                                                    <option>select</option>
                                                </select>
                                            </li>
                                            <li>
                                                <label><span>*</span>Zip/Postal Code</label><input id="zip" name="zip"  class="sml" type="text">
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list2">
                                            <li>
                                                <input id="weelChairAccessible1" name="weelChairAccessible" type="checkbox" value="weelChairAccessible" name="chk">
                                                <label for="weelChairAccessible1">Office is wheelchair accessible (optional)</label>
                                            </li>
                                            <li>
                                                <input id="twoBlocksFromPublicTransport1" name="twoBlocksFromPublicTransport" type="checkbox" value="twoBlocksFromPublicTransport" name="chk">
                                                <label for="twoBlocksFromPublicTransport1">Office is within 2 blocks of public transportation (optional)</label>
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list2">                           
                                            <li>
                                                <label class="line_height"> <span>*</span> Office Phone (Please entet the data with no punctuation)</label>
                                            </li>
                                            <li>
                                                <input name="officePhone" id="officePhone" placeholder="(NPA) NXX-XXXX" type="text">
                                            </li>                           
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list2">                           
                                            <li>
                                                <label class="line_height"> <span>*</span> My office takes calls between:</label>
                                            </li>
                                            <li>
                                                  <select name="takesCallsStart" class="select_list selectBox takesCallsStart" data-hasqtip="686">
                                                    <option value="1">1</option>
                                                    <option value="2">2</option>
                                                    <option value="3">3</option>
                                                    <option value="4">4</option>
                                                    <option value="5">5</option>
                                                    <option value="6">6</option>
                                                    <option value="7">7</option>
                                                    <option value="8">8</option>
                                                    <option value="9">9</option>
                                                    <option value="10">10</option>
                                                    <option value="11">11</option>
                                                    <option value="12">12</option>
                                                  </select>
                                                  <input id="takesCallsStartSuffix1"type="checkbox" value="AM" data-id="1" name="takesCallsStartSuffix" checked> 
                                            </li>
                                            <li>
                                                <label class="line_height">and</label>
                                            </li>
                                            <li>
                                              <select name="takesCallsEnd" class="select_list selectBox takesCallsEnd" data-hasqtip="688">
                                                <option value="1">1</option>
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                                <option value="4">4</option>
                                                <option value="5">5</option>
                                                <option value="6">6</option>
                                                <option value="7">7</option>
                                                <option value="8">8</option>
                                                <option value="9">9</option>
                                                <option value="10">10</option>
                                                <option value="11">11</option>
                                                <option value="12">12</option>
                                              </select>

                                              <input id="takesCallsEndSuffix1" data-id="1"  type="checkbox" name="takesCallsEndSuffix" checked> 
                                            </li>   
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list2">                           
                                            <li>
                                                <label class="line_height"> Fax (Please enter the data with no punctuation)</label>
                                            </li>
                                            <li>
                                                <input id="fax" name="fax" placeholder="(NPA) NXX-XXXX" maxlength="14" type="text">
                                            </li>                           
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list2">                           
                                            <li>
                                                <label class="line_height"> Alternate Office Phone (Please enter the data with no punctuation)</label>
                                            </li>
                                            <li>
                                                <input id="altOfficePhone" name="altOfficePhone" maxlength="14" placeholder="(NPA) NXX-XXXX" type="text">
                                            </li>                           
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="form_colom_list">
                                            <li>
                                                <label for="businessEmail"><span>*</span>Business Email Address</label><input name="businessEmail" id='businessEmail' class='businessEmail' type="text" class="big_sml" />
                                            </li>
                                        </ul>
                                    </div>                  

                                    <div class="form_row">
                                        <label><span>*</span>Client emails are responded to by:</label>
                                    </div>  

                                    <div class="form_row">
                                        <ul class="form_colom_list2">
                                            <li>
                                                <input id="emailProcessedByMe" name="emailProcessedByMe" type="checkbox" value="emailProcessedByMe" checked>
                                                <label for="emailProcessedByMe">Me personally</label>
                                            </li>
                                            <li>
                                                <input id="emailProcessedByStaff1" name="emailProcessedByStaff" type="checkbox" value="emailProcessedByStaff">
                                                <label for="emailProcessedByStaff1">My staff</label>
                                            </li>
                                        </ul>
                                    </div>                  

                                    <div class="form_row">
                                        <ul class="form_colom_list2">                           
                                            <li>
                                                <label class="line_height"> <span>*</span> Number of busines days emails are responded to:</label>
                                            </li>
                                            <li>
                                                <select name = 'emailRespondedBy' class="select_list selectBox">
                                                    <option>1</option>
                                                    <option>2</option>
                                                    <option>3</option>
                                                </select>
                                            </li>                               
                                        </ul>
                                    </div>

                                    <div class="form_row">
                                        <ul class="redioButtons otherOffices form_colom_list2">                         
                                            <li>
                                                <label> Do you have offices in other locations?</label>
                                            </li>
                                            <li>
                                                <input id="otherOfficeRadioYes1" type="radio" name="otherOfficeRadio1" class="css-checkbox" value="y">
                                                <label for="otherOfficeRadioYes1">Yes</label>
                                            </li>
                                            <li>
                                                <input type="radio" id="otherOfficeRadioNo1" name="otherOfficeRadio1" class="css-checkbox" value="n">
                                                <label for="otherOfficeRadioNo1">No</label>
                                            </li>
                                        </ul>
                                    </div>
                                  </div>

最佳答案

我发现不能使用 jQuery 的 replaceWith() 方法进行递归替换。一旦索引 1 的元素被替换,replaceWith() 方法就没有任何可匹配的内容(原始元素已被替换),因此迭代器运行一次,更改所有值,然后停止。

关于javascript - jQuery concat 变量输入名称未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34302656/

相关文章:

javascript - 相互更改两个选择元素

javascript - 如何更改禁用控件的颜色

javascript - 为什么即使没有 src 标签,图像 'complete' 属性也总是返回 true?

jQuery 可用时间选择器

javascript - 在 UIWebView 中调试 JS

javascript - 如何使用javascript调用其他javascript(如这段代码)?

javascript - knex js 查询生成器性能

javascript - jQuery "hasParent"

javascript - 在 extjs 3.4 中刷新面板中的数据 View

javascript - 在包含许多元素的页面中更喜欢 id 属性还是 data 属性?