2011-05-13 68 views
0

基本上我有以下幾點:我想保持JQuery的排序狀態,當我去到一個新的頁面

  1. 正在使用jQuery和更新使用Ajax
  2. 隱藏的對象存儲名稱排序表排序國家(列名)+(ASC或DESC)
  3. ,在阿賈克斯的無限循環結束jQuery的方法調用

我想:

  1. 要能夠使用will_paginate,請導航到新頁面並保持用戶選擇的排序。
  2. 我快到了。我只需要你的幫助;我是新的JQuery/Ajax

這是我的代碼。第一種方法,效果很好。第二個讓我陷入無盡的循環。在此先感謝您的幫助!

$('.overview_table_header').click(function() { 
    header = $(this) 
    var col2 = $.trim($(this).text()) 
    var sort2 = header.data('sort') 
    $.get("/sort", { 
     col: $.trim($(this).text()), 
     sort: header.data('sort') 
    }, function(data) { 
     $('#pages').html(data.html); 
     header.data('sort', data.sort); 
    }); 
    $(".secretdata").data("test", { 
     first: sort2, 
     last: col2 
    }); 
    $(".secretdata h2:first").text($(".secretdata").data("test").first); 
    $(".secretdata h2:last").text($(".secretdata").data("test").last); 
}); 


$('.overview_table_header').ready(function() { 
    header = $('.overview_table_header') 
    var col = $(".secretdata h2:first") 
    var sort = $(".secretdata h2:last") 

    $.get("/sort", { 
     col: col, 
     sort: sort 
    }, function(data) { 
     $('#pages').html(data.html); 
     header.data('sort', data.sort); 
    }); 
}); 

回答

1

第二個函數只能在頁面加載時執行一次,對嗎?

因此,而不是$('.overview_table_header').ready(function() {只需使用$(function() {,這是document.ready/document.onLoad的縮寫。

循環可能正在發生,因爲ajax回調改變了'.overview_table_header'中的某些內容,再次觸發.ready()

我會如下重寫代碼:

$('.overview_table_header').click(function() { 
    sort($(this)) 
}); 

$(function() { // when page is loaded 
    sort() 
}); 

sort(param) { 
    var col, dir; 
    dir= $("#sortDirection").val(); 
    if (!param) { // first run 
     col = $("#sortColumn").val(); 
    } else { 
     col = $.trim(param.text()); // This is dangerous! (1) 
     $("#sortColumn").val(col); 
    } 
    $.get("/sort", { col: col, sort: dir}, 
    function(data) { 
     $('#pages').html(data.html); 
     $("#sortDirection").val(data.sort); 
    } 
); 
}); 

的secretdata會變成這樣:

<input type="hidden" id="sortColumn" name="sortColumn" value="date" /> 
<input type="hidden" id="sortDirection" name="sortColumn" value="asc" /> 

一些注意事項:

  • 不使用的名稱,如secretdata /首/末爲了存儲你的變量,將來處理這些代碼的人會變得非常困惑(甚至在幾個月後)。
  • 您更好的存儲這個東西在隱藏的輸入,如果您提交的形式,他們甚至會自動傳播
  • (1)$.trim(param.text());獲取列名是很危險的,你最好通過例如歸列名在data-columnName屬性,檢索它與.data("columnName")
  • 我不明白爲什麼你存儲的方向兩次(secredata和頭:數據排序),所以我改變了只有一個存儲位置。
+0

感謝您試圖幫助,但這不起作用 – 2011-05-13 16:26:08

+0

什麼不工作? – ariel 2011-05-13 17:54:48

相關問題