下面的代码有效。如果有更好的方法请告诉我。 如果我使用主页中 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>
测试.html:
<h1 class='heading'>Page via AJAX</h1>
<script>
$(function(){
$('.heading').on('click',function(){
$(this).css('color','red');
});
});
</script>
我们必须通过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>
测试.html:
<h1 class='heading'>Page via AJAX</h1>
最佳答案
这是因为您正在将事件绑定(bind)到文档准备就绪。您必须使用委托(delegate)才能使其工作。喜欢on 。这是因为 .header 加载时不在页面上。因此没有附加任何事件。
你的代码应该看起来像这样:
$('body').on('click','.heading',function(){
$(this).css('color','red');
});
它不一定是正文,而是文档准备好后不加载的元素,它是 .heading 的父元素。
关于Jquery 事件不适用于 ajax 加载的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620211/