代码之家  ›  专栏  ›  技术社区  ›  ShoeLace1291

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

  •  0
  • ShoeLace1291  · 技术社区  · 7 年前

    这是我的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.'));
                }
            }
        })
    

    <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 回复  |  直到 7 年前
        1
  •  0
  •   ACD    7 年前

    下面的代码将只替换文本而不指定它。

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

    在替换文本后必须赋值才能更新实际值。

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