【发布时间】:2021-11-06 07:39:24
【问题描述】:
我正在按价格和字母顺序对商品进行排序。 它按字母顺序排序非常好。它正在排序价格数组,但不根据排序后的价格打印对象。在 console.log 中一切都做得很完美,但是当我选择价格从低到高的选项时,它不会对项目进行任何更改,而在控制台中进行。
$(document.body).on('change', '#products-sorting', function() {
var priceArr = [];
var nameArr = [];
for (var i = 0; i < tempArr.length; i++) {
var price = $(tempArr[i]).find('.addToWishlist').data("price").replace("$", "");
var name = $(tempArr[i]).find('.addToWishlist').data("name");
priceArr.push(price)
nameArr.push(name);
}
//sort by Price
for (var n = 0; n < priceArr.length; n++) {
for (var i = 0; i < tempArr.length; i++) {
//sort price low to high
if ($(this).val() === 'Price, low to high') {
priceArr.sort(function(a, b) {
return a - b
})
}
//sort price high to low
if ($(this).val() === 'Price, high to low') {
priceArr.sort(function(a, b) {
return b - a
})
}
var price = $(tempArr[i]).find('.addToWishlist').data("price").replace("$", "");
if (priceArr[n] == price)
$("#product-items").append(tempArr[i])
}
}
//console.log(priceArr)
//sort Alphabetically
for (var n = 0; n < nameArr.length; n++) {
for (var i = 0; i < tempArr.length; i++) {
//sort alphabetically A to Z
if ($(this).val() === 'Alphabetically, A to Z')
nameArr.sort();
//sort alphabetically Z to A
if ($(this).val() === 'Alphabetically, Z to A') {
nameArr.sort();
nameArr.reverse()
}
var name = $(tempArr[i]).find('.addToWishlist').data("name");
if (nameArr[n] == name)
$("#product-items").append(tempArr[i])
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="select-box" class="clearfix">
<label for="products">Sort by</label>
<select name="products" id="products-sorting">
<option value="Featured">Featured</option>
<option value="Alphabetically, A to Z">Alphabetically, A to Z</option>
<option value="Alphabetically, Z to A">Alphabetically, Z to A</option>
<option value="Price, low to high">Price, low to high</option>
<option value="Price, high to low">Price, high to low</option>
</select>
</div>
【问题讨论】:
-
什么是
tempArr? -
为什么你的排序有循环?您应该对数组进行一次排序,然后循环遍历结果以更新表格。
-
我有一个包含 html 内容(tempArr)的对象数组。这就是为什么我需要循环。
-
我从那个数组中检索价格和名称来制作单独的数组
-
但是每次循环都在对同一个数组进行排序。排序不会改变。
标签: javascript jquery arrays sorting price