使用Handlebars.js助手使用jQuery创建活动元素? [英] Using Handlebars.js helpers to create active elements with jQuery?
问题描述
是否可以在Handlebars.js助手中使用jQuery创建元素并将事件处理程序附加到它们上?我希望能够使用助手创建活动元素。
Is it possible to within a Handlebars.js helper to create elements using jQuery and attach event handler to them? I'd like to be able to create active elements using helpers.
示例:
Handlebars.registerHelper("button", function(title) {
var button = $('<button>').text(title);
button.click(function() {
alert("Button " + title + " clicked.");
});
return $('<div>').append(button).html();
});
在句柄模板中,我实例化这个按钮:
In the handlebars template I instantiate the button like this:
{{{button "Click Me!"}}}
据我所知,这是行不通的,因为jQuery的html()函数移除事件处理程序......但仅仅返回按钮显然不起作用。
Handlebars助手应该能够返回DOM节点,但这是不可能的,对吧?我试图返回 button.get(),但没有成功。
I understand that this can not work, since the jQuery's html() function `removes' the event handler... but simply returning button obviously does not work either. Handlebars helpers should be able to return DOM nodes, but this is not possible, right? I tried to return button.get(), but without success.
有什么想法?
推荐答案
函数在 registerHelper
之外被调用onClick。所以代码如下所示:
What you could do is create a function outside of registerHelper
to be called onClick. So the code for that would look like this:
Handlebars.registerHelper("button", function (text) {
var button = $('<button></button>').text(text).attr('onclick', 'button_clickEvent()');
return $('<div></div>').append(button).html();
});
var button_clickEvent = function () {
alert("Button " + $(this).text() + " clicked.");
};
这篇关于使用Handlebars.js助手使用jQuery创建活动元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!