2011-10-25 85 views
2

至于下面的函数,我已经在过去的时间重写了十几次:递归调用Ajax

function show_history() { 
    $('.job.collapsed').click(function() { 
     $(this).removeClass('collapsed'); 
     $(this).addClass('expanded'); 
     $(this).children('.bottom').load('expand.php', function(){ 
      $('.job.expanded').click(function() { 
       $(this).removeClass('expanded'); 
       $(this).addClass('collapsed'); 
       $(this).children('.bottom').html(''); 
       $(show_history); 
      }); 
     }); 
    }); 
} 

这一点我最初称这样:

$(document).ready(function() { 
    $('#main').load('jobs.php', show_history); 
}); 

的第一时间我点击一个'.job',1个请求发送到'expand.php'

第二次点击也会向'expand.php'发送1个请求,尽管'.job'没有'.collapsed'类。

第三届点击发送2个请求,第4发3个请求,5号发送6个请求,第六发送请求9,第7发送18名的请求,8日发送27个请求等

我想它在单击折叠作业时发送1个请求,当单击扩展作业时没有请求。

我该如何解决这个问题?

编辑

我使用的解决方案的基础上,@ mblase75的建议:

function show_history() { 
    $('.job.collapsed').live('click',function() { 
     $(this).removeClass('collapsed'); 
     $(this).addClass('expanded'); 
     $(this).children('.bottom').load('expand.php'); 
    }); 
    $('.job.expanded').live('click',function() { 
     $(this).removeClass('expanded'); 
     $(this).addClass('collapsed'); 
     $(this).children('.bottom').html(''); 
    }); 
} 

回答

1

请尝试移动.click走出回调,并用.live("click")处理程序替换为:

$('.job.expanded').live('click',function() { 
     $(this).removeClass('expanded'); 
     $(this).addClass('collapsed'); 
     $(this).children('.bottom').html(''); 
     $(show_history); 
    }); 
    $(this).children('.bottom').load('expand.php'); 
+0

这使我在正确的轨道上。将'.job.expanded'和'.job.collapsed'事件分开,将它们设置为'.live('click')'并停止调用该函数。精彩地工作。 – Chris

+0

@Chris很高兴听到它 - 不要忘记接受你最喜欢的答案。 http://meta.stackexchange.com/q/5234/171394 – Blazemonger

0

我相信代码中可能存在一个缺陷:“.job.expanded”是一个类,我屁股梅,被给予同一页面中的多个项目。因此,$(这)将适用于所有的项目在页面

可能的解决办法:

$('.job.expanded').live('click',function() { 
var $thisID = $(this.id); 
$thisID.removeClass('expanded'); 
$thisID.addClass('collapsed'); 
$thisID.children('.bottom').html(''); 
$(show_history); 
}); 

哦,是的,我已经失去了一束头发上类似的代码固定自己,希望有救了你一些你自己.....