I open a html page with a myApp.js included like this:
<html>
<body>
......
<div id="dynamicForm"></div>
......
<script type="text/javascript" src="myPath/myApp.js"></script>
......
</body>
</html>
and then I want to load a form defined in myApp.js dynamically on this html page at (“#dynamicForm”), the myApp.js has some lines like this:
.....
//load the form on the html page
$('#dynamicForm').html(createDynamicForm()).show();
.....
//the function creating the form
function createDynamicForm(){
var jqForm=$('<form id="dynamicFormId">'
......
+ '<button id="btn">OK</button>'
+ '</form>');
$('body').append(jqForm);
return jqForm;
}
.....
//click the button on the form to trigger the alert box
("#btn").click(function(){
alert("you click the button");
});
I can load the form on the html page, but when I click the “OK” button on this dynamically loaded form, the alert doesn’t pop up, apparently this is because myApp.js is loaded with the html page before the dynamic form is created, the “click” event can not be handled by the handler defined in myApp.js that creates the form. how can I fix this problem?
As you’re trying the
#btndynamically, so you need a delegate event handler and for that purpose you should use.on().Syntax of
.on()for delegate event looks:Here,
staticElementpoints to an element that belongs to DOM at page load i.e. which is not dynamic.