简体   繁体   中英

JavaScript replace in jQuery html()

I am facing a little problem in JavaScript. I have a template that I use to add some fields to my form:

 <div id="personTemplate" style="display: none;">
    <s:url id="personneList" action="personneList" namespace="/ajax" />
    <sj:autocompleter name="personnesContacts[ID_XXX]"
        id="nomPersonne_IDXXX" forceValidOption="false"
        key="label.serviceContacts" href="%{personneList}" />
</div>

With jQuery, I get the content in my personTemplate div, which is :

<input id="nomPersonne_IDXXX" name="personnesContacts[1]" type="hidden">
<input autocomplete="off" class="ui-autocomplete-input" name="personnesContacts[ID_XXX]_widget" id="nomPersonne_IDXXX_widget" type="text">
<span class="ui-helper-hidden-accessible" aria-live="polite" role="status"></span>
<script type="text/javascript">
    jQuery(document).ready(function () {
        var options_nomPersonne_IDXXX_widget = {};
            options_nomPersonne_IDXXX_widget.hiddenid = "nomPersonne_IDXXX";
            options_nomPersonne_IDXXX_widget.selectBox = false;
            options_nomPersonne_IDXXX_widget.forceValidOption = false;

            options_nomPersonne_IDXXX_widget.jqueryaction = "autocompleter";
            options_nomPersonne_IDXXX_widget.id = "nomPersonne_IDXXX_widget";
            options_nomPersonne_IDXXX_widget.name = "personnesContacts[ID_XXX]_widget";
            options_nomPersonne_IDXXX_widget.href = "/baseline/ajax/personneList.action";
        jQuery.struts2_jquery_ui.bind(jQuery('#nomPersonne_IDXXX_widget'),options_nomPersonne_IDXXX_widget);
    });
</script>

I tried to replace IDXXX by a number, but it is only in the name attribute that this occurrence is changed. May be you have an idea of how to replace IDXXX when I get the div content like this :

<script type="text/javascript">
counter = 0;
function addMorePersons() {
    counter++;
    var text = $('#personTemplate').html();
    text = text.replace("ID_XXX", counter);
    $(text).insertAfter($('#personnesContact_0_widget'));

}

您需要一个全局替换函数,如果使用正则表达式,则可以告诉它替换所有内容:

text = text.replace(/ID_XXX/g, counter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM