如何通过在 JavaScript 中更新 DOM 中的产品顺序来按价格对数组中的项目进行排序

问题描述 投票:0回答:1

所以我的 php 块位于“shop.php”的开头,如下所示:

<?php
$jsonPath = './product.json';
$jsonString = file_get_contents($jsonPath);
$data = json_decode($jsonString);
?>

这可以完美地从我的“products.json”文件中获取我的数据。

我也有我的下拉菜单,如下所示:

 <!-- Dropdown menu to trigger sorting start -->
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="triggerId">
    <a class="dropdown-item" href="#" id="sortByName">Name</a>
    <a class="dropdown-item" href="#" id="sortByPrice">Price</a>
    <a class="dropdown-item" href="#" id="sortByReview">Review </a>
    <a class="dropdown-item" href="#" id="sortBySaving">Saving </a>

</div>
<!-- Dropdown menu to trigger sorting end -->

还有我的 foreach 代码块,如下所示:

<!-- for each start -->
<?php foreach ($data as $key => $jsons) {
    foreach ($jsons as $key => $product) {
?>
        <div class="col-lg-4 col-md-6 col-sm-12 pb-1">
            <div class="card product-item border-0 mb-4">
                <div class="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
                    <img class="img-fluid w-100" src="img/<?php echo $product->img; ?>.jpg" alt="">
                </div>
                <div class="card-body border-left border-right text-center p-0 pt-4 pb-3">
                    <h6 class="text-truncate mb-3"><?php echo ucfirst($product->name); ?></h6>
                    <div class="d-flex justify-content-center">
                        <h6>$<?php echo ($product->price); ?></h6>
                        <?php
                        if ($product->was_price == false) {
                        } else {
                            echo "<h6 class='text-muted ml-2'>Was <del>$$product->was_price</del></h6>";
                        }
                        ?>
                        <?php
                        if ($product->reviews == false) {
                        } else {
                            echo "<h6 class='text-muted ml-2'><span>$product->reviews</span>% Review Score </h6>";
                        }
                        ?>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-between bg-light border">
                    <a href="" class="btn btn-sm text-dark p-0"><i class="fas fa-eye text-primary mr-1"></i>View Detail</a>
                    <a href="" class="btn btn-sm text-dark p-0"><i class="fas fa-shopping-cart text-primary mr-1"></i>Add To Cart</a>
                </div>
            </div>
        </div>

<?php
    }
}



?>
<!-- for each end -->

我想按四个类别进行排序:

  • 名字
  • 价格
  • 回顾和
  • 节省

我已经成功地用我的名字排序:

<script>
document.addEventListener("DOMContentLoaded", function() {
// Get the dropdown items
var sortByName = document.getElementById('sortByName');
var sortByPrice = document.getElementById('sortByPrice');
var sortByReview = document.getElementById('sortByReview');
var sortBySaving = document.getElementById('sortBySaving');

// Add click event listeners to trigger sorting functions
sortByName.addEventListener("click", function() {
    sortItemsByName();
});

sortByPrice.addEventListener("click", function() {
    sortItemsByPrice();
});

sortByReview.addEventListener("click", function() {
    sortItemsByReview();
});

sortBySaving.addEventListener("click", function() {
    sortItemsBySaving();
});

// Define sorting functions (implement these functions)
function sortItemsByName() {
    // Sort products by name
    var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

    // Get all product items
    var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

    // Sort product items by name
    productItems.sort(function(a, b) {
        var nameA = a.querySelector('.text-truncate').textContent.trim().toUpperCase();
        var nameB = b.querySelector('.text-truncate').textContent.trim().toUpperCase();

        if (nameA < nameB) {
            return -1;
        }
        if (nameA > nameB) {
            return 1;
        }
        return 0;
    });

    // Update the order of product items in the DOM
    productItems.forEach(function(item) {
        productContainer.appendChild(item);
    });
}
</script>

我正在尝试对价格、评论和节省进行排序,但不起作用。

这是我尝试过的

<script>
// Define sorting functions
function sortItemsByPrice() {
  // Sort products by price
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by price (assuming prices are numeric)
  productItems.sort(function(a, b) {
    var priceA = parseFloat(a.querySelector('.text-center h6').textContent.replace('$', ''));
    var priceB = parseFloat(b.querySelector('.text-center h6').textContent.replace('$', ''));

    return priceA - priceB;
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

function sortItemsByReview() {
  // Sort products by review score
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by review score (assuming reviews are numeric)
  productItems.sort(function(a, b) {
    var reviewA = parseInt(a.querySelector('.text-muted span').textContent);
    var reviewB = parseInt(b.querySelector('.text-muted span').textContent);

    return reviewB - reviewA; // Sorting in descending order (highest review first)
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

function sortItemsBySavings() {
  // Sort products by savings
  var productContainer = document.querySelector('.row.pb-3'); // Adjust the selector accordingly

  // Get all product items
  var productItems = Array.from(productContainer.querySelectorAll('.col-lg-4.col-md-6.col-sm-12.pb-1'));

  // Sort product items by savings (assuming savings are numeric)
  productItems.sort(function(a, b) {
    var savingsA = parseFloat(a.querySelector('.text-muted del').textContent.replace('$', ''));
    var savingsB = parseFloat(b.querySelector('.text-muted del').textContent.replace('$', ''));

    return savingsB - savingsA; // Sorting in descending order (highest savings first)
  });

  // Update the order of product items in the DOM
  productItems.forEach(function(item) {
    productContainer.appendChild(item);
  });
}

});
</script>

请问我出了什么问题,我该如何解决这个问题才能成功对价格、评论和节省进行排序?谢谢

javascript php html jquery sorting
1个回答
0
投票

let products = [
  { name: 'Product A', price: 30 },
  { name: 'Product B', price: 20 },
  { name: 'Product C', price: 25 },
  // ... add more products
];

// Sort array by price
products.sort((a, b) => a.price - b.price);

// Update DOM order
let costrong textntainer = document.getElementById('productContainer'); // Replace with the actual ID or class
container.innerHTML = '';

products.forEach(product => {
  let productElement = document.createElement('div');
  productElement.textContent = `${product.name} - $${product.price}`;
  container.appendChild(productElement);
});

© www.soinside.com 2019 - 2024. All rights reserved.