JQuery event inside a underscore.js template

99封情书 提交于 2019-12-13 14:07:00

问题


I'm having trouble including javascript code inside an underscore.js template (particularly a jquery .click() event). I've tried many variations of the <% .. %> tags, and here is my latest:

 <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);
        });
     }); %>

Any help will be appreciated. Thanks


回答1:


That's not a good idea. The code would be executed during the evaluation of the template, not when (or after) the produced HTML is inserted into the DOM. But you need that to make the jQuery selectors working.

So, separate behaviour from content!

<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"));
    });


来源:https://stackoverflow.com/questions/17612576/jquery-event-inside-a-underscore-js-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!