2011-11-28 18 views
0

我們有100多張圖片。每個圖像有3個參數:如何過濾/排序jquery中的圖像/塊?

  • 年(2007 | 2008 | 2009)
  • 顏色(紅色|黃色|藍色)
  • 類型(肖像|全景)

我怎麼樣使用此參數的頁面上的圖像(我希望看到blue + panorams + 2007),而無需重新加載頁面 - 只需選擇正確的圖像?

P.S.我不知道如何簽名參數,在我沒有使用外部文件類class =「2009黃色藍色肖像」類我guses

+1

請1)顯示您的標記,2)defi ne「選擇」 – Alnitak

+1

更重要的是,請定義參數的分配方式。 – Blazemonger

回答

0

這是一般的想法。您需要創建一個真正的圖像數組,然後使用JavaScript array.sort和自定義函數對它們進行排序。一旦完成,您可以將其返回到DOM,然後他們將重新排列。

arrImages = $('img').get(); // need a true array 
arrImages.sort(function(a,b) { 
    // write your own sort function here using your parameters 
    // return a negative number to sort a before b, positive to sort b before a 
}); 
$.each(arrImages, function(i,el) { 
    $('#container').append(el); 
}); 
2

我要去假設下面的標記...你可以使其適應自己:

<div id="images"> 
    <div> 
    <img src="..." /> 
    <em>Year: </em><span class="year">2007</span> 
    <em>Color: </em><span class="color">red</span> 
    <em>Type: </em><span class="type">portrait</span> 
    </div> 
    <div> 
    <img src="..." /> 
    <em>Year: </em><span class="year">2008</span> 
    <em>Color: </em><span class="color">yellow</span> 
    <em>Type: </em><span class="type">panoram</span> 
    </div> 
</div> 

那麼這是jQuery的你將需要:

function sortBy(field) { 
    var container = $('#images'); 
    // get a real array of the image divs 
    var imgDivList = container.children().get(); 
    // Put them into the correct order based on the chosen field 
    imgDivList.sort(function (a, b) { 
     var aText = $(a).children('.' + field).text(); 
     var bText = $(b).children('.' + field).text(); 
     if (aText < bText) { 
      return 1; 
     } 
     if (aText > bText) { 
      return -1; 
     } 
     if (aText == bText) { 
      return 0; 
     } 
    }); 
    // Append them back to the original container 
    container.append(imgDivList); 
} 

對於過濾,請執行此操作:

function filter(field, value) { 
    var imgDivList = $('#images').children(); 
    imgDivList.each(function (index, element) { 
     if ($(element).children('.' + field).text() == value) { 
      $(element).show(); 
     } else { 
      $(element).hide(); 
     } 
    }); 
}