以下代码有效.如果有更好的方法请告诉我.如果我使用主页中test.html中存在的脚本内容,我通过ajax加载test.html.该脚本不起作用.
<html>
<head>
<script src='jquerylocation' type='text/javascript'></script>
</head>
<body>
<div id='ajaxload'></div>
<button class='test'>load content via ajax</button>
</body>
<script>
$(function(){
$('.test').on('click',function(){
$('#ajaxload').load('test.html');
});
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
的test.html:
<h1 class='heading'>Page via AJAX</h1>
<script>
$(function(){
$('.heading').on('click',function(){
$(this).css('color','red');
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
我们必须通过ajax加载脚本以及动态加载的内容,以便按需要工作.但我觉得每次发送ajax请求脚本时都会加载内容.但我发现只有这个解决方案.如果有人知道更好的解决方案请回复
例如,如果以这种方式更改代码它将无法工作.
<html>
<head>
<script src='jquerylocation' type='text/javascript'></script>
</head>
<body>
<div id='ajaxload'></div>
<button class='test'>load content via ajax</button>
</body>
<script>
$(function(){
$('.test').on('click',function(){
$('#ajaxload').load('test.html');
});
$('.heading').on('click',function(){
$(this).css('color','red');
});
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
的test.html:
<h1 class='heading'>Page via AJAX</h1>
Run Code Online (Sandbox Code Playgroud)
Pet*_*sen 53
这是因为您在文档准备就绪时绑定了事件.您必须使用委托才能使其正常工作.喜欢上.这是因为.header在加载时不在页面的页面上.所以没有附加任何事件.
您的代码应该看起来像这样:
$('body').on('click','.heading',function(){
$(this).css('color','red');
});
Run Code Online (Sandbox Code Playgroud)
它不必是body,而是在文档就绪后未加载的元素,它是.heading的父元素.