我有一个Ajax网站,Ajax内容来自其他网页,如about.html,contact.html。 ajax从一个名为#main-content的div获取内容。但在ajax调用之后,其余的脚本都会中断。如tinyscrollbar()插件和一些其他自定义函数。.live()或.livequery()
我搜索了大约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;
});
你通常应该比.live()更喜欢.delegate(),这是更高性能的。另外,我不认为有很多livequery可以做到这一点.live或委托现在不能。 – Robin 2011-02-06 16:28:57