我打开一个包含myApp.js的html页面,如下所示:
<html>
<body>
......
<div id="dynamicForm"></div>
......
<script type="text/javascript" src="myPath/myApp.js"></script>
......
</body>
</html>
然后我想在这个html页面(“#dynamicForm”)上动态加载myApp.js中定义的表单,myApp.js有这样的行:
.....
//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");
});
我可以在html页面上加载表单,但是当我单击此动态加载表单上的“确定”按钮时,警报不会弹出,显然这是因为myApp.js之前加载了html页面创建动态表单时,创建表单的myApp.js中定义的处理程序无法处理“click”事件。我该如何解决这个问题?
答案 0 :(得分:3)
当您动态尝试#btn
时,您需要一个委托事件处理程序,为此,您应该使用 .on()
。
$('body').on('click', '#btn', function(){
alert("you click the button");
});
委托事件的.on()
语法:
$(staticElement).on( eventName, target, handlerFunction );
这里,staticElement
指向页面加载时属于DOM的元素,即不是动态的。