index.js
$(function(){
$("#btn").on("click",function(){
$.ajax({
url: 'page.html',
type: 'post',
success: function (responseText) {
$('#div1').html(responseText);
}
});
});
$("#test").on("click",function(){
alert('hello world!');
});
});
demo.html
<script type="text/javascript" src="index.js"></script>
<input type="button" id="btn" value="加载" />
<div id="div1"></div>
page.html
<input type="button" id="test" value="执行" />
请问:
当demo页面加载page页面后,html代码就会被加载到div1容器里面,之间加载的index.js对于新内容不起作用,点击执行按钮是无效的。
请问如何让加载的页面中javascript代码能够执行?
实践场景:页面依赖第三方表单验证(通过class属性定义验证规则),动态新添加了表单元素,可是新表单元素的验证规则不起作用。
插入的脚本是不能被执行的~
jquey的html方法使用了原生的innerHTML属性,而对这个属性的赋值时,其中的script标签中的代码将会被无视,不会被解析。
但是加载元素属性上的JS代码是可以被执行的
如: