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

如何在jquery中将文本替换成HTML?

  •  1
  • alastairs  · 技术社区  · 15 年前

    我有一个从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 }
    }
    

    如您所见,模板中的某些项被多次替换(即, 爱迪克斯 )

    webapp在整个过程中已经广泛使用jquery,所以我想知道是否有一种更类似jquery的方式来实现这一点,可能使用dom,而不是依赖于字符串操作。

    有什么想法吗?

    2 回复  |  直到 15 年前
        1
  •  1
  •   Pointy    15 年前

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

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

        2
  •  0
  •   Aaron Digulla    15 年前

    element_idx_Icon