2011-02-06 24 views
3

我有一个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; 

    }); 
+0

你通常应该比.live()更喜欢.delegate(),这是更高性能的。另外,我不认为有很多livequery可以做到这一点.live或委托现在不能。 – Robin 2011-02-06 16:28:57

回答

7

对于插件,无论是真的。你可以简单地重新初始化中$.load是你的插件完成回调:

$('#main-content').load(toLoad, function() { 
    $("#foo").tinyscrollbar(); 
    $("#bar").facebox(); 
    // etc 
}); 

事件处理程序,您可以在回调中重新绑定他们在上面的例子中,或使用.live.delegate(你似乎已经是使用),以确保结合持续未来(Ajax的替换)元件,例如:

$('.projects dl').delegate("dt", "hover", function() { 
    ... 
}, function() { 
    ... 
}); 

或:

$('.projects dl dt').live("hover", function() { 
    ... 
}, function() { 
    ... 
}); 
+0

真的吗?将所有脚本加载到.load()下? – nowayyy 2011-02-06 16:28:21