我目前正在设计一个基于ajax 的导航网站。我遇到的问题是,当我尝试在动态加载的内容上运行 jquery 时,它不起作用。
这是我所做的:
index.html
<html>
<head>
<title>Testing Dynamic Content</title>
<link href="style.css" rel="stylesheet"/>
<script src="http://localhost/jquery.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="main">
<div class="content">
<ul class="list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</div>
</div>
<script>
$('.list').greenify();
</script>
</body>
</html>
2.html
<html>
<head>
<title>Testing Dynamic Content</title>
<link href="style.css" rel="stylesheet"/>
<script src="http://localhost/jquery.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="main">
<div class="content">
<span id="hello">Content</span>
</div>
</div>
<script>
$('#hello').on('click',function(){
$('.main').load('index.html .content');
$('.list').greenify();
});
</script>
</body>
</html>
样式.css
.list{
color:#f00;
}
main.js
$.fn.greenify = function() {
this.css( "color", "red" );
};
问题出在$('list').greenify();中。当我使用 .load() 在 2.html 上加载 index.html 的内容时,内容会按照 css 中的定义以红色加载。当我对此加载的内容运行 $('list').greenify() 时,它不起作用。
如何运行才能在动态加载的内容上运行 JavaScript?
我需要这样做才能使幻灯片在动态加载的网页上运行。并且幻灯片无法正常工作。
最佳答案
问题是您的代码在页面成功加载之前运行,请将您的代码移至文档就绪事件:
$(document).ready(function(){
$('.list').greenify();
})
并且 jQuery 加载是异步的,您需要在成功函数中运行 javascript
$('.main').load('index.html .content', function() {
//will execute when load successfully
$('.list').greenify();
});
关于javascript - 在基于 ajax 的网站的动态加载内容上运行 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27763429/