javascript - 如何替换 jQuery DOM 元素中的字符串

标签 javascript jquery string replace

我需要从 jQuery ajax 响应构建 HTML。我不喜欢在 javascript 中嵌套难看的字符串,我不想使用 mustache 或任何其他模板脚本。

所以我采用了带有 display: none 的模板 HTML 的方法:

<div id="message-template" class="message-tile" style="display: none;">
    <div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
    <div class="message-data">
        <div class="message-info">
            <div class="sender-name">
                <a href="{{person-url}}">{{person-name}}</a>
            </div>
            <div class="posted-to">
                To <a href="{{posted-to-url}}">{{posted-to-title}}</a>
            </div>
        </div>
        <div>{{message-body}}</div>
    </div>
</div>

我希望能够用 json 对象中的实际值替换 {{ }} 之间的字符串。 假设这是在 jQuery.ajax onSuccess 事件上调用的函数:

function createNewElement(jsonObj) {
    var $clone = $('#message-template').clone();
    $clone.replaceString("{{person-name}}", jsonObj.personName);
    $clone.replaceString("{{thumb-url}}", jsonObj.thumbUrl);
    $clone.replaceString("{{person-url}}", jsonObj.personUrl);
    // etc
    $("#target-container").append($clone);
}

我发明了 replaceString 方法,但是有类似的东西吗?或者我是否需要使用 find() 遍历每个子元素?

最佳答案

实际上你可以使用<script type = "text/template">创建您自己的模板,这样它就不会呈现在您的页面上:

<script id="message-template" type = "text/template">

    <div class="message-tile" style="display: none;">
        <div class="profile-thumb"><img src="{{thumb-url}}" width="48" height="48" alt="{{person-name}}" /></div>
        <div class="message-data">
            <div class="message-info">
                <div class="sender-name">
                    <a href="{{person-url}}">{{person-name}}</a>
                </div>
                <div class="posted-to">
                    To <a href="{{posted-to-url}}">{{posted-to-title}}</a>
                </div>
            </div>
            <div>{{message-body}}</div>
        </div>
    </div>

</script>

以下是您如何替换您的值:

function createNewElement(jsonObj) {
    var $clone = $('#message-template').html();
    $clone = $clone.replace("{{person-name}}", jsonObj.personName)
                   .replace("{{thumb-url}}", jsonObj.thumbUrl)
                   .replace("{{person-url}}", jsonObj.personUrl);
    // etc
    $("#target-container").append($clone);
}

关于javascript - 如何替换 jQuery DOM 元素中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443413/

相关文章:

javascript - 网络音频 API : How do I add a working convolver?

javascript - 质量和自动身份验证

php - 使用 Ajax 将 Javascript 变量传递给 PHP

c++ - 无法将 ‘std::string {aka std::basic_string<char>}’ 转换为 ‘char’ 作为返回

python - 如何格式化字符串以在 Python 中使用 mysqldb 进行查询?

javascript - 访问唯一的嵌套 JSON 数组项

javascript - 将javascript集成到wordpress主题中

jQuery 不会触发标签标签上的点击

javascript - JQUERY 旋转 img

javascript - 将不同 DIV 中的数字相加