簡體   English   中英

如何在jQuery中將文本替換為HTML?

[英]How to substitute text into HTML in jQuery?

我有一個從Javascript函數返回的模板HTML:

function getTemplate() {
    return '<li id="element_idx_" class="elementChoice">' +
           '  <a href="#" onclick="_clickScript_" tabindex="27" title="_toolTip_">' + 
           '    <span id="element_idx_title">_elementDisplayText_</span>' + 
           '    <div class="elementIcon" id="element_idx_image"></div>' +
           '    <div class="actionIcon" id="element_idx_Icon"></div>' +
           '  </a>' +
           '</li>';
}

子字符串_idx__clickScript_等,使用從AJAX調用中檢索到的數據替換,使用的函數定義類似於:

function interpolate(template, replacements) {
    // * template is the HTML listed above
    // * replacements is a JavaScript object, where the property names map to 
    //   the substitution strings in the HTML template.
    // 
    // E.g., { idx: 4, clickScript: function() { // click }, displayName: foo }
}

如您所見,某些項在模板中被替換了多次(即_idx_ )。

該Web應用程序已經在整個過程中廣泛使用jQuery,因此我想知道是否還有一種類似jQuery的方式來實現這一目標,也許使用DOM,而不是依賴於字符串操作。

有什么想法嗎?

好吧,約翰·雷西格(John Resig)在博客中發表了有關將這樣的模板放入腳本塊的博客:

<script id='template1' type='text/html'>
  <li id='element_idx' ...
    ...
  </li>
</script>

瀏覽器不會嘗試解釋這些內容,但是您可以獲取以下文本:

var template = $('#template1').text();

這比將模板放入Javascript稍微干凈一些,但這並非沒有問題。 將模板與代碼分開可能會有些麻煩或尷尬,具體取決於您的設置。

因為在那些用DOM操作難以到達的地方(例如element_idx_Icon )替換了這些字符串,所以沒有了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM