2012-02-29 22 views
1

我有這樣的jQuery腳本:jQuery的獲取文件每次切換()被調用錯誤

$(".show-div").data('loaded',false).click(function() { 
    $.post("script.php", {id_1: var_id_1, id_2: var_id_2}, function(data){ 
     $(this).data('loaded',true); 
     $("#display").html(data); 
    }); 

    $("#display").toggle('fast'); 
    return false; 
}); 

加載一個頁面(script.php的),並顯示其從當前頁面的#display DIV中的內容。現在,我想要做的只是在第一次單擊.show-div時加載script.php,但每次都會加載它。爲什麼?我究竟做錯了什麼?

+0

你可能會想在第一次成功呼叫後刪除點擊處理程序,其他將在整個時間保持綁定狀態。 – j08691 2012-02-29 21:25:34

+0

@ j08691。但他仍然想'切換'#顯示' – gdoron 2012-02-29 21:26:51

回答

2
$(".show-div").click(function() { 
    if (!$(this).data('loaded')) // <==== 
    { 
     $.post("script.php", {id_1: var_id_1, id_2: var_id_2}, function(data){ 
      $("#display").html(data); 
      $(this).data('loaded',true); 
     }); 
    } 

    $("#display").toggle('fast'); 
    return false; 
}); 

另一種方式去:

$(".show-div").one('click', function() { 
    $.post("script.php", { id_1: var_id_1, id_2: var_id_2}, function(data) { 
      $("#display").html(data);}); 
    return false; 
}).click(function() { 
    $("#display").toggle('fast'); 
    return false; 
});​ 
1

檢查數據( '裝')是真的,不要讓Ajax調用,如果它是

$(".show-div").click(function() { 
    var $this = $(this); 
    /* check if loaded*/ 
    if (!$this.data('loaded')) {// only call ajax first time 
     $.post("script.php", {id_1: var_id_1,id_2: var_id_2}, function(data) { 
      $this.data('loaded', true); 
      $("#display").html(data); 
     }); 

    } 
    $("#display").toggle('fast'); 
    return false; 
}); 
+1

'$(「。show-div」)。data('loaded',false).click'不需要初始化數據加載,因爲默認情況下它是未定義的.. – gdoron 2012-02-29 21:38:05

相關問題