问题
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