2011-02-12 182 views
0

如何使這樣的:如何使函數在ajax調用中調用函數?

$('.projects').hover(function(){ 
    $defBox.stop(true, true).fadeToggle(1000).html('test'); 
}); 

成一個函數,然後調用它在一個Ajax調用?

// 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, log); 
    } 

    function hideLoader() { 
     $loadimg.fadeOut('fast'); 
    } 
    return false; 
}); 

我的功能

$('.projects dl').find('dd').hide(); 

    function fadeBox(){ 
    $('#def-box').stop(true, true) 
     .fadeToggle(1000) 
     .html('test'); 
    } 

    $('.projects').hover(function(){ 
    fadeBox(); 
    }); 
    function descBox(){ 
    $('.projects dl').find('dd').hide(); 
    var $data = $(this) 
     .next('dd') 
     .html(); 
    $('#def-box').html($data); 
    } 

    $('.projects dl dt').hover(function(){ 
    descBox(); 
    }); 

和Ajax

function showNewContent() { 
     fadeBox(); 
     descBox(); 
     $content.fadeIn('fast',hideLoader); 
    } 

而且這是行不通的。它假設當dt被徘徊時,其隱藏的dd元素位於它在#def-box中的位置。

function descBox(){ 
    $('.projects dl').find('dd').hide(); 
    var $data = $(this) 
     .next('dd') 
     .html('test'); 
    $('#def-box').html($data); 
} 

另外,dd元素,如果我點擊anotherpage隱藏,但在負荷... http://example.co/#homedd不是隱藏不動了。

+0

使它成爲一個函數很容易,用函數(){`和`}`包圍它。但現在確定我明白你的意思,用AJAX調用它 - 在AJAX返回時運行它嗎? – 2011-02-12 18:31:53

+0

是的,這是我的意思 – nowayyy 2011-02-12 18:53:33

回答

1
// create the function 
function myfunc(){ 
    $defBox.stop(true, true).fadeToggle(1000).html('test'); 
} 

    // use it as the handler 
$('.projects').hover(myfunc); 

    // call it in the showNewContent function 
function showNewContent() { 
    myfunc(); 
    $content.fadeIn('fast',hideLoader, log); 
}