例如,我有以下名为 index.html
的 HTML:
<html>
<head>
<style>
#content { float:left; }
#sub { float:right; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="action.js"></script>
</head>
<body>
<h2>Test de</h2>
<div id="content">
Content
<button class="loadSub">Load</button>
</div>
<div id="sub">
Sub content
</div>
</body>
</html>
还有一个名为 action.js
的简单 JS 文件:
$(document).ready(function(){
$('button.loadSub').click(function(){
$('#sub').load('test.html');
});
$('button.hide').click(function(){
$('#sub').fadeOut('slow');
});
});
如您所见,当我单击按钮 .loadSub
时,div #sub
将加载 test.html
中的新内容>:
<h2>This is the sub content</h2>
<button class="hide">Hide</button>
我在这里遇到两个问题:
首先,.loadSub
按钮确实成功加载了id为subcontent
的div,但是.hide
按钮不起作用。
其次,在我尝试插入之后
script type="text/javascript" src="action.js"
在test.html
内,隐藏按钮起作用并淡出其内容。但反过来,我发现按钮 loadSub
不再起作用。我无法再次加载子内容
。
有没有其他方法可以只声明一次 js 文件的源并让我的 button.loadSub
在我单击它时工作?有人可以解释一下这个问题并给我一个解决它的提示吗?
最佳答案
您正在将动态 HTML 加载到您的页面中。这意味着在您调用 $('button.hide').click()
时,页面中尚不存在 button.hide
元素,因此无法附加 click
处理程序。
您可能想尝试执行委托(delegate)
附件。
$('#sub').on('click', 'button.hide', function () {
$('#sub').fadeOut('slow');
});
关于javascript - 将内容加载到 div 后 jQuery 停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10636669/