2011-05-26 43 views
0

的名單上有div的列表,如:更新DIV

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'"> 
    <div class="categories1"> 
     Andy 
    </div> 

    <div class="categories2"> 
     Link to Andy 
    </div> 
</div> 

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'"> 
    <div class="categories1"> 
     Mark 
    </div> 

    <div class="categories2"> 
     Link to Mark 
    </div> 
</div> 

... 

<div class="categories" onmouseover="this.style.background='#CCCCCC'" onmouseout="this.style.background='#FFFFFF'"> 
    <div class="categories1"> 
     Yuri 
    </div> 

    <div class="categories2"> 
     Link to Yuri 
    </div> 
</div> 

由名稱排序裏面categories1

通過AJAX/jQuery我添加到服務器一個新的類別,並在此操作後,我想更新客戶端上的列表。

所以,我認爲這些方式:

  1. 的插入的一個後,選擇從數據庫中的所有類別,創建整個HTML並刷新舊的一個新一個;作爲編碼的解決方案速度更快,但如果列表太長,開銷很大;

  2. 從服務器只加載創建的元素,瀏覽DOM trought jQuery,檢查放置元素的位置(檢查字母順序)並添加它;

沒有一個聽起來不錯,所以我會問你一些建議/提示/想法。

謝謝

回答

2

進行AJAX調用以獲取新元素。將它附加到你的包含div。然後排序的所有div的名字使用 - >

//get a raw array of dom nodes 
var items = $('.categories1').get(); 

//empty out the container 
$('#container').empty(); 

//use Array's prototype sort() method 
items.sort(function(x,y) { 
    return $(x).text() > $(y).text(); 
}); 

//iterate through their sorted order, appending their parent back to the container 
$(items).each(function() { 
    $('#container').append($(this).parent()); 
}); 

這裏有一個小提琴看到它在行動 - http://jsfiddle.net/rz3Ww/

+0

+1非常優雅的解決方案。如果列表很大,可以將'.empty()'語句移動到'sort()'之前,以防止處理時出現無序內容的閃爍。顯然'append()'需要保持最後! :) – 2011-05-26 12:40:53

+0

@Chris好的建議 - 如果需要的話,這也是放置加載啓動畫面的好地方。 – 2011-05-26 12:45:27

+0

試過你的例子,但實際上它沒有做正確的排序:檢查出這個http://jsfiddle.net/rz3Ww/1/:Gabba應該在GTW之前,而不是之後... – markzzz 2011-05-26 13:05:50

1

我傾向於去與你的第二個建議 - jQuery的可以非常迅速地抓住所有的元素的類型爲category1,並且從這裏解析文本到一個數組中是很繁瑣的。然後,你需要做的是找出哪個元素就在你的新元素之前,在DOM中找到它,然後添加你的元素。

1

兩件事情浮現在腦海中閱讀您的問題後:

  1. 你是在談論一個列表,但你使用的DIV。這不是世界末日,但是使用無序列表(<ul>)在語義上更合適。
  2. 既然你提出了jQuery,這個問題乞求使用jQuery Templates plugin。您正在嘗試執行客戶端數據綁定,這正是jQuery模板可以幫助您做的事情。