Let’s imagine that we have some piece of html with appended actions.
var html = $('<a href="#">click me</a>');
html.find('a').bind('click', function(e) {
alert('You clicked me!');
});
Now we want append this piece of html (with binded actions) to some <div id="destination"></div>.
$('#destination').append(html);
Is it possible? (see jsfidder)
I need this functionality to bind some actions for modal window’s content and then append this content to modal window’s html wrapper and then invoke Modal.show(). So
Is it good practice or it is not recommended to do?
The concept should work fine. The problem with your fiddle is the use of
find, which looks at descendant elements, but youraelement isn’t a descendant. Usefilterinstead:Here’s an updated fiddle.
Alternatively, you could use
on(if you’re using jQuery 1.7+) ordelegateto attach the event handler to#destination:If you do that, you may want to give the
aelement some identifier, otherwise the event handler will execute for anyadescendant of#destination.Edit (based on comments)
As noted by @RoryMcCrossan in the comments, in this case you can actually remove
filtercompletely. This is because there is just the one element in the jQuery object. However, if you’ve shortened the code for the purposes of the question, be careful, as removingfilterin that case would bind the event handler to all of the elements: