2011-10-25 86 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); 
}); 

哦,是的,我已經失去了一束頭髮上類似的代碼固定自己,希望有救了你一些你自己.....