Underscore.js 模板 IE9 / IE10 没有返回正确的代码

Underscore.js template IE9 / IE10 not returning right code

我的 js 文件中有这段代码

var selectedTagElement = _.template('$("#selected_tag_item_template").html()', item = { tag: label, value: value });
$('#wrapper_id').append(selectedTagElement); 

这在我的 html 文件中

    <script type="text/template" id="selected_tag_item_template">
      <div class="tag_item selected js-selected_tag_item" 
           data-tag-value="<%= item.value %>" 
           data-tag-label="<%= item.tag %>"><%= item.tag %>
      </div>
    </script>

在除 IE9 和 IE10 之外的所有浏览器中一切正常。如果它尝试

console.log(selectedTagElement)

我得到的只是

LOG: function(n){return o.call(this,n,m)} 

如果我尝试在我的 html 文件中打印项目变量,就像这样

<%= item %>

我明白了

function item() { [native code] }

怎么了?谢谢

您获得的输出:

console.log(selectedTagElement)

表示selectedTagElement是一个函数。你以前可以一步编译和填写一个模板,但是 stopped working in Underscore 1.7.

您需要分两步开始构建您的 selectedTagElement

  1. 使用 _.template.
  2. 将模板编译为函数
  3. 运行 与所需数据一起运行以获得您的 HTML.

所以你想这样说:

var t = _.template($('#selected_tag_item_template').html());
var selectedTagElement = t({ item: { tag: label, value: value } });

这应该适用于任何地方并符合标准用法。


你的代码在它能正常工作的地方意外地工作。我将假设 '$("#js_template").html()' 只是一个拼写错误,否则它没有任何意义。让我们将您的代码分解为等效的代码:

item = { tag: label, value: value };
var selectedTagElement = _.template('$("#js_template").html()', item);
$('#wrapper_id').append(selectedTagElement); 

第一行创建一个全局 item 变量,其中包含您要提供给模板的数据。

第二行将模板编译成函数并完全忽略第二个 item 参数,因为它与 _.template 的任何选项都不匹配。

第三行把函数交给了[append]2。通常你给 append 一串 HTML 或一个 DOM 节点,但你也可以给它一个函数;当您给 append 一个函数时,它会运行该函数并将其 return 值用作 HTML 字符串。在非 IE 浏览器中,模板函数将通过您的意外全局变量获得 item

item = { tag: label, value: value }

但 IE 从某处使用 item 函数(在浏览器中使用本机代码实现)而不是使用您的 item 变量。