How do I add a simple onclick on a JavaScript mustache template?

非 Y 不嫁゛ 提交于 2019-12-10 17:48:40

问题


I have a simple mustache template:

var template = "<button style='background: red;'>{{label}}</button>";

And the data:

var data = {

    label: "Click me!"

}

Which works great with when doing the classic transformation:

var html = Mustache.to_html( template, data );

But my question. How do I add a simple onclick function on my button, which I define in the indata?


回答1:


Add an "onclick" atribute with code to execute as an argument.

<button onclick='alert("I was called!")' style='background: red;'/>




回答2:


var template = "<button style='background: red;'>{{onclick}}</button>";

var data = {

    onclick: function(){
             // content of your function 
             }

}

The answer of JanL is right in essence




回答3:


I think the point of the question is that your page should not need to wire up events until it knows what template it may or may not be using. Load your template from an external html file and add a script with your events underneath your template definition




回答4:


Using jQuery's built-in .on('click') event handler:

$("button").on('click', function() {
  alert("I was clicked!");
});


来源:https://stackoverflow.com/questions/8391955/how-do-i-add-a-simple-onclick-on-a-javascript-mustache-template

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