我有一个网站是Ajaxed,内容是Ajax是从其他页面,如about.html,contact.html。ajax从一个名为#main-content的div中获取内容。但是在ajax调用之后,我的其他脚本中断了。比如tinyscrollbar()插件和其他一些自定义函数。
我搜索了大约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;
});发布于 2011-02-07 00:24:05
对于插件来说,两者都不是。你可以简单地在$.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() {
...
});https://stackoverflow.com/questions/4914486
复制相似问题