我有一个Ajaxed的网站,Ajax的内容来自其他页面,例如about.html,contact.html。 ajax 从名为 #main-content 的 div 获取内容。但是在 ajax 调用之后,我的其余脚本就中断了。比如tinyscrollbar()插件和其他一些自定义函数。
我搜索了大约 4 天,发现我的问题是 AJAX 请求更改 DOM,并且由于脚本在此之前加载,因此在 ajax 调用之后它不会运行。
如果我是对的,我需要什么来解决这个问题? .live() 还是 .livequery() 插件?
我使用的所有JS都在这:
var $dd = $('.projects dl').find('dd'), $defBox = $('#def-box');
$defBox.hide();
$('.projects').hover(function(){
$defBox.stop(true, true)
.fadeToggle(1000)
.html('<p>Hover The links to see a description</p>');
});
$dd.hide();
$('.projects dl dt').hover(function(){
var $data = $(this).next('dd').html();
$defBox.html($data);
});
// Ajax Stuff
// Check for hash value in URL
var hash = window.location.hash.substr(1);
// Check to ensure that a link with href == hash is on the page
if ($('a[href="' + hash + '"]').length) {
// Load the page.
var toLoad = hash + '.php #main-content';
$('#main-content').load(toLoad);
}
$("nav ul li a").click(function(){
var goingTo = $(this).attr('href');
goingTo = goingTo.substring(goingTo.lastIndexOf('/') + 1);
if (window.location.hash.substring(1) === goingTo) return false;
var toLoad = $(this).attr('href')+' #main-content',
$content = $('#main-content'), $loadimg = $('#load');
$content.fadeOut('fast',loadContent);
$loadimg.remove();
$content.append('<span id="load"></span>');
$loadimg.fadeIn('slow');
window.location.hash = goingTo;
function loadContent() {
$content.load(toLoad,'',showNewContent)
}
function showNewContent() {
$content.fadeIn('fast',hideLoader);
}
function hideLoader() {
$loadimg.fadeOut('fast');
}
return false;
});
对于插件来说,两者都不是。您只需在其中重新初始化您的插件即可$.load
的完整回调:
$('#main-content').load(toLoad, function() {
$("#foo").tinyscrollbar();
$("#bar").facebox();
// etc
});
对于事件处理程序,您可以在回调中重新绑定它们,如上例所示,或者使用.live
or .delegate
(您似乎已经在使用)以确保绑定对于未来(ajax 替换的)元素仍然存在,例如:
$('.projects dl').delegate("dt", "hover", function() {
...
}, function() {
...
});
or:
$('.projects dl dt').live("hover", function() {
...
}, function() {
...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)