JavaScript:string.replace不起作用

7
我有一个小问题,需要在JavaScript/jQuery中替换字符串。首先是代码:
HTML:
<fieldset>
    <legend>Contact persons</legend>
    <div id="cm_contactPersons">
        <fieldset id="cm_%email%">
            <legend><span class="glyphicon glyphicon-circle-arrow-right"></span> %email%</legend>
            <div class="form-group">
                <label for="cm_%email_inputFirstname" class="col-sm-2 control-label">Firstname</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="cm_%email%_inputFirstname" value="%firstname%" placeholder="" required>
                </div>
            </div>
            <div class="form-group">
                <label for="cm_%email%_inputLastname" class="col-sm-2 control-label">Lastname</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="cm_%email%_inputLastname" value="%lastname%" placeholder="i. e. Max" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">Actions</label>
                <div class="col-sm-10">
                    <button type="button" class="btn btn-warning">Create new password</button>
                    <button type="button" class="btn btn-danger">Delete contact person</button>
                </div>
            </div>
        </fieldset>
    </div>
</fieldset>

JavaScript:

$(document).ready(function() {
    $('#cm_customerList').btsListFilter('#cm_customerSearchInput');
    var editingArea = $('#cm_editingArea');
    var contactPersons = $('#cm_contactPersons');
    var contactPersonsTpl = contactPersons.html();
    var alertArea = $('#cm_alertArea');

    $('#cm_customerList > a').each(function() {
        $(this).click(function(e) {
            e.preventDefault();
            $('#cm_customerList>a.active').removeClass('active');
            $(this).addClass('active', 400);
            $('html').animate({
                scrollTop: 0
            });
            alertArea.fadeOut(400, function() {
                alertArea.empty();
            });
            $.ajax({
                type: 'GET',
                url: 'index.php?' + $(this).attr('data-ajaxUrl'),
                success: function(data) {
                    res = $.parseJSON(data);
                    editingArea.fadeOut(400, function() {
                        $('#cm_inputName').val(res.name);
                        $('#cm_inputStreet').val(res.street);
                        $('#cm_inputPostalcode').val(res.postalcode);
                        $('#cm_inputCity').val(res.city);
                        $('#cm_inputCountry option[value="' + res.country + '"]').prop('selected', true);
                        $('#cm_inputCountry').select2({
                            width: '100%'
                        });
                        $('#cm_inputTutors option:selected').prop('selected', false);
                        $.each(res.tutors, function(key, tutor) {
                            $('#cm_inputTutors option[value="' + tutor.username + '"]').prop('selected', true);
                        });
                        $('#cm_inputTutors').select2({
                            width: '100%'
                        });
                        contactPersons.empty();
                        $.each(res.contactpeople, function(key, contactPerson) {
                            contactPersons.append(contactPersonsTpl.replace('%email%', contactPerson));
                        });
                        editingArea.fadeIn();
                    });
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    //error handler
                }
            });
        });
    });
});

contactPersons.append(contactPersonsTpl.replace('%email%', contactPerson));” 这部分代码中的替换操作不起作用。我尝试了各种调试方法(日志、更改 substr 等),但都没有成功。
但是,如果我在 Firefox 控制台中编写“$('#cm_contactPersons').html().replace('%email%', 'test@blubb.at');”,它就可以工作。
我做错了什么?

2
如果我在Firefox控制台中写入[...],它就能正常工作。那么string.replace确实有效吗? - Chris Martin
@ChrisMartin 是的,但只能在 Firefox 控制台中。 - Cheesi
@zamnuts 是的,你可能是正确的。 - Cheesi
2个回答

5

使用正则表达式(regex).. JSFIDDLE

默认情况下,replace只会更改模式的第一个出现。为了替换字符串中的所有模式,您需要使用带有g修饰符的正则表达式。

contactPersons.append(contactPersonsTpl.replace(/%email%/g, contactPerson));

是的,谢谢,它有效 :) 但为什么使用substr不起作用?而且为什么在Firefox控制台中可以工作? - Cheesi

0

变量contactPersonsTpl是字符串而不是jQuery对象。因此,您不能使用.append()。您应该使用jQuery对象来使用.append()。像这样:

var contactPersonsTpl = $('#cm_contactPersons');
contactPersonsTpl.append(contactPersonsTpl.html().replace('%email%', contactPerson));

contactPersonsTpl.html()的结果是字符串,所以这个结果将保持不变。至少在第一次之后,它将包括在前几次迭代中添加的内容(和先前的事件)。 - Guffa
问题不在于追加(这个没问题),而在于替换。 - Cheesi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接