.live()或.livequery()

我有一个Ajax的站点,Ajax的内容来自其他页面,例如about.html,contact.html。 ajax从一个叫做#main-content的div中获取内容。 但在ajax调用之后,我的其余脚本都会中断。 比如tinyscrollbar()插件和一些其他自定义函数。

我搜索了大约4天,发现我的问题是更改DOM的AJAX请求,并且由于脚本在此之前被加载,因此在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('

Hover The links to see a description

'); }); $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(''); $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; });

对于插件,不是真的。 你可以简单地在$.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() { ... });