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