如何在ajax调用中创建函数并调用函数?

时间:2011-02-12 18:27:36

标签: jquery 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);  
    } 

这也行不通。当dd悬停时,它会隐藏#def-box元素,使其隐藏在dt中。

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

如果我点击其他页面,dd元素也会被隐藏,但在加载时... http://example.co/#home dd不再隐藏。

1 个答案:

答案 0 :(得分: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);  
}