admin管理员组文章数量:1406741
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.
Example:
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!"}}}
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.
Any ideas?
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.
Example:
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!"}}}
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.
Any ideas?
Share Improve this question edited Sep 13, 2021 at 18:47 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 5, 2011 at 11:14 Stefan K.Stefan K. 1681 silver badge8 bronze badges1 Answer
Reset to default 3What 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.");
};
本文标签: javascriptUsing Handlebarsjs helpers to create active elements with jQueryStack Overflow
版权声明:本文标题:javascript - Using Handlebars.js helpers to create active elements with jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744849895a2628433.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论