3

我无法在 underscore.js 模板中包含 javascript 代码(尤其是 jquery .click() 事件)。我尝试了许多 <% .. %> 标签的变体,这是我最新的:

 <script type="text/html" id="eventTemplate">
  <% _.each(words, function(word) { %>
      <a data-role="button" id="eventButton <%= word %>" href="#" data-icon="plus" data-iconpos="right">
          <%= word %>
      </a>
     <% $('#eventButton' + word +').click(function() {
         console.log(word);
        });
     }); %>

任何帮助将不胜感激。谢谢

4

1 回答 1

4

这不是一个好主意。代码将在模板评估期间执行,而不是在生成的 HTML 插入 DOM 时(或之后)执行。但是你需要它来使 jQuery 选择器工作。

因此,将行为与内容分开

<script type="text/html" id="eventTemplate">
<% _.each(words, function(word) { %>
    <a href="#" data-role="button" class="eventButton" data-word="<%= word %>" data-icon="plus" data-iconpos="right">
        <%= word %>
    </a>
<% }) %>
</script>
// then:
    var html = _.template(eventTemplate, data);
    $(domElement).html(html).on("click", ".eventButton", function(e) {
        console.log($(this).data("word"));
    });
于 2013-07-12T10:49:45.757 回答