Reputation: 3259
I need to create button dynamically and assign its onclick
handler. Click handler could be anonymous function (I'm not sure how it is called in JS). It is allowed to jQuery
.
I tried something like this:
<div>
<button id="x">Show</button>
</div>
function magick() {
console.log('some special magick');
}
function createButton(itsHandler) {
var guts = '<button id="__internal" onclick="'
+ itsHandler + // <-- that's wrong
'">Test</button>';
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton(magick);
});
});
but is doesn't work.
How it can be accomplished?
UPD1: It would be better if it was done inside of the createButton
function.
Upvotes: 4
Views: 15714
Reputation: 473
You may use on() for binding events on dynamically added elements. Like this:
$(document).on('click', '#__internal', function () {
alert('some special magick');
})
Upvotes: 0
Reputation: 40639
Try to use on() like
$('body').on('click','#__internal',function(){
console.log('test some special magick');
});
$(document).ready(function () {
$("#x").bind("click", function() {
var guts = '<button id="__internal" >Test</button>';
$($.trim(guts)).appendTo('body');
});
});
Updated In your code, below two lines
can create magic
for you like,
var guts = '<button id="__internal">Test</button>';
$($.trim(guts)).appendTo('body').bind('click', magick);
Upvotes: 13
Reputation: 2488
I think you can do it that way just make onclick value a function call like this:
var guts = '<button id="__internal" onclick="magick()">Test</button>';
But it won't work in jsfiddle, because jsfiddle put your js code in window load handler so the magick function would not be visible outside that handler.
And about your createButton function you should pass the function's name instead of the function itself, try this:
function createButton(itsHandlerName) {
var guts = '<button id="__internal" onclick="'
+ itsHandlerName +
'()">Test</button>';//add () to the function's name
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton("magick");//pass function name
});
});
Upvotes: 0