2012-08-22 33 views
0

我正在使用JQuery.load()将文件的内容拉入网页。把这个关闭的JavaScript是在一个单独的.js文件中,以保持整洁。使用jquery.load并试图避免包含相同的代码两次

/* Pulls in file contents */ 
    $(function() { 
    $('.div').load('file.html'); 
}); 

然而,当文件在我使用的交叉淡出图片jQuery的动画拉 - 的代码,这也是在.js文件 - 不工作。

/* Crossfade code */ 
$(function(){ 
$(".appearing-image img").css("opacity",0).fadeTo(300, 0); 
$(".appearing-image img").mouseover(function() { 
     $(this).fadeTo(200, 1); 
    }); 
$(".appearing-image img").mouseout(function() { 
     $(this).fadeTo(200, 0); 
    }); 
}); 

我发现让它工作的唯一方法是将它包含在.load()代码中。

/* Pulls in file contents and executes animation */ 
$('.div').load('file.html',  $(function(){ 
      /* Crossfade images */ 
      $(".appearing-image img").css("opacity",0).fadeTo(300, 0); 
      $(".appearing-image img").mouseover(function() { 
      $(this).fadeTo(200, 1); 
      }); 
      $(".appearing-image img").mouseout(function() { 
      $(this).fadeTo(200, 0); 
      }); 
     }); 
    }); 

这是行得通的。

但是,在页面的其他地方,除非代码本身也包含在代码中,否则其他图片将不会交叉淡化,与.load()分开,这意味着我现在包含代码两次。

有没有办法避免这种情况?

+0

使用'。对( “鼠标悬停” 装载的东西,function()...'或使用函数 – mplungjan

回答

2

使用外部功能,比如像crossfade()

/* Crossfade code */ 
function crossfade(){ 
$(".appearing-image img").css("opacity",0).fadeTo(300, 0); 
$(".appearing-image img").mouseover(function() { 
     $(this).fadeTo(200, 1); 
    }); 
$(".appearing-image img").mouseout(function() { 
     $(this).fadeTo(200, 0); 
    }); 
} 

/* Pulls in file contents and executes animation */ 
$('.div').load('file.html', function(){ 
    /* Crossfade images */ 
    crossfade(); 
}); 
0

您可以使用

$(window).bind('setup', function() { 
    //code 
}); 

文档之前准备

相关问题