如何用jQuery中的变量对象替换HTML中的变量?

时间:2018-11-15 03:57:42

标签: javascript jquery

我试图为我的网页创建一个系统,该系统获取HTML中找到的模板的内容,然后将适当的变量替换为存储在对象中的相应值。问题是什么都没有被取代。在此示例中,我获取了显示论坛帖子的RSS文件的内容。我使用ajax来获取内容,然后遍历每个项目。我将xml标记值分配给一个对象,该对象的键与HTML模板中的变量相对应。对于找到的每个帖子,都应该用xml标签的内容替换HTML变量。

这是我的Javascript:

$.ajax({
        url: "rsstest.xml",
        type: "GET",
        dataType: 'xml',
        crossDomain: true,
        success: function(xml){
            var news = $('#news-results');
            news.empty();
            if($(xml).find('item').length > 0){
                $(xml).find('item').each(function(){
                    var temp_vars = {
                            news_title: $(this).find('title').text(),
                            news_body: $(this).find('description').text(),
                            news_date: $(this).find('pubDate').text(),
                            news_link: $(this).find('link').text()
                    }
                    var template = $('#news-template').contents().clone();
                    for(const variable in temp_vars){
                        template.text().replace("{"+variable+"}", temp_vars[variable])
                    }
                    news.append(template);
                })
            } else {
                news.append($('<p></p>').text('There is no news to display at this time.'));
            }
        }
    })

这是我的HTML:

<h1>Announcements</h1>
<div id="news-results">
</div>
<div id="news-template" style="display: none;">
    <div class="media">
        <div class="media-body">
            <h3>{news_title}</h3>
            <p>{news_body}</p>
            <div class="media-footer">
                <div class="col-left">
                    <h4>Posted on {news_date}</h4>
                </div>
                <div class="col-right">
                    <a href="{news_link}" class="btn btn-default">Read More</a>
                </div>
            </div>
        </div>
    </div>
</div>

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

下面的代码将仅替换文本而不分配文本。

template.html().replace("{"+variable+"}", temp_vars[variable])

替换文本后,您必须进行分配以更新实际值。

template.html(template.html().replace("{"+variable+"}", temp_vars[variable]))