如何通过创建事件的javascript中定义的处理程序处理事件?

时间:2012-06-29 11:39:39

标签: javascript jquery events dynamic handler

我打开一个包含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”事件。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

当您动态尝试#btn时,您需要一个委托事件处理程序,为此,您应该使用 .on()

$('body').on('click', '#btn', function(){
    alert("you click the button");
});

委托事件的.on()语法:

$(staticElement).on( eventName, target, handlerFunction );

这里,staticElement指向页面加载时属于DOM的元素,即不是动态的。

相关问题