undercore.js模板中的JQuery事件 [英] JQuery event inside a underscore.js template

查看:115
本文介绍了undercore.js模板中的JQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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.

所以,与内容分开的行为

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

这篇关于undercore.js模板中的JQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆