Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  6] [ 7]  / answers: 1 / hits: 15604  / 11 Years ago, wed, november 13, 2013, 12:00:00

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.


More From » jquery

 Answers
201

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


[#74316] Monday, November 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joep

Total Points: 32
Total Questions: 97
Total Answers: 104

Location: Wales
Member since Thu, Jul 1, 2021
3 Years ago
;