![](/img/trans.png)
[英]How can I change the content of a div using jquery and javascript?
[英]How can I sort div elements based on inner div element content / values using javascript / jQuery?
我在一個頁面中有 X 個 div,每個 div 項代表一個產品,如下所示:
<div class="productContainer">
<li>
<img src="my-product-image.jpg"></a>
<div class="productInfo">
<h4>
<!-- SORT ALL DIVS BASED ON A TAG CONTENT -->
<a class="productTitleForSorting" href="product-page-link">NAME</a><br>
</h4>
<div class="product-price">
<span id="lowestPrice">PRICE:
<!-- OR SORT ALL DIVS BY PRODUCT PRICE SPAN CONTENT -->
<span class="productPriceForSorting">$XX.XX</span></span>
</div>
</div>
</li>
</div>
然后我有一個 select 列表/下拉列表,我想從其中按價格或字母順序對 div 進行排序。
例如,假設我有 10 個 div(10 個產品),就像上面的一個頁面一樣。 我希望能夠在 select 列表更改上按標題(a.productTitleForSorting 內容)或價格(span.productPriceForSorting)進行排序。
有什么想法我可以 go 關於用 Javascript / jQuery 完成此任務嗎? 它必須在客戶端完成。
我嘗試使用數據排序插件,但沒有運氣,所以尋找新的想法和建議。 謝謝!
我不建議對 dom 進行排序和重新排序。 如果必須在客戶端完成,則存儲 javascript 數組並對其進行排序。 例如:
var items = [{price:3,name:"something"}, {price:10,name:"somethingelse"}];
現在使用JavaScript 排序函數將這個和 append 排序到 dom。 這比在 dom 對象周圍移動要高效得多。
您可以使用本機排序 function,但問題是您必須提供比較機制:
function sortByPrice(a,b){
return $(a).find('.productPriceForSorting').text() > $(b).find('.productPriceForSorting').text();
}
然后您可以使用以下方法對元素進行排序:
$('.productContainer').sort(sortByPrice);
對元素進行排序后,您需要更新 html,因此您應該清空產品容器,然后按新順序 append 排序元素:
function reorderEl(el){
var container = $('#productList');
container.html('');
el.each(function(){
$(this).appendTo(container);
});
}
把它們放在一起:
reorderEl($('.productContainer').sort(sortByPrice));
這是一個工作示例: http://jsfiddle.net/gion_13/jKJc3/
使用類似這樣的排序插件,您只需要比較器功能,例如:
function sortByTag(a, b) {
$(a).find('a').first().text() > $(b).find('a').first().text();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.