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.
(Here is jsfiddled code)
How it can be accomplished?
UPD1: It would be better if it was done inside of the createButton function.
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');
    });
}); 
Demo
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);
Demo 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With