اذهب إلى المحتوى
  • 1

مشكلة في ترتيب مجموعة من المنتجات حسب السعر في جافاسكريبت JavaScript

Shamma Mohammed

السؤال

السلام عليكم 

عندي مشكلة مع هذا الكود الفونكشن الاولى function FilterProduct()  هذه تعمل صح 

لكن الفونكشن الثانية function SortProduct()  لاتعمل متلخبطة ماتترتب بحسب السعر لااعرف مالمشكلة 

كود HTML

<html>
<head>
  <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link rel="stylesheet" href="bootstrap-4.1.3-dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="fontawesome-5/fontawesome-css/all.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- style CSS -->
    <link rel="stylesheet" href="css/shop.css">
</head>
<body>
  <!-- Navigation section
   ================================================== -->
<?php include"nav.php"; ?>
<!-- Header section
================================================== -->
<section id="portfolio">
      <div class="container">
         <div class="row">

            <div class="col-md-12 col-sm-12">
              <div class="iso-section wow fadeInUp" >
          <ul class="indicator clearfix">
            <li data-filter="all" class="active opc-main-bg"><a href="#">All Dress</a></li>
            <li data-filter="long" class="opc-main-bg"><a href="#">long Dress</a></li>
            <li data-filter="short" class="opc-main-bg"><a href="#">short Dress</a></li>
            <li data-filter="mediam" class="opc-main-bg"><a href="#">mediam Dress</a></li>
          </ul>
          <div class="filter-condition">
      <span>View As a</span>
      <select name="" id="select">
        <option value="Default">Default</option>
        <option value="LowToHigh">Low to high</option>
        <option value="HighToLow">High to low</option>
      </select>
    </div>
       <div class="iso-box-section wow fadeInUp" >
             <div class="iso-box-wrapper col4-iso-box">
               <ul class="items">
                 <li data-category="" data-price="">
                   <div class="iso-box col-md-4 col-sm-6">
                      <div class="portfolio-thumb">
                 <img src="img/pexels-maksim-goncharenok-4424269.jpg" class="img-responsive" alt="Portfolio"/>
                     </div>
               <div class="detail">
                 <h2>Mango</h2>
     						<strong>long</strong>
     						<span>Lorem, ipsum dolor sit amet consectetur.</span>
<h4>$50.78</h4>
     						<a href="#"><i class="fas fa-shopping-cart"></i></a>
                <a href="#"><i class="fas fa-heart"></i></a>
               </div>
     					</div>

               </li>

               <li data-category="" data-price="">
                 <div class="iso-box col-md-4 col-sm-6">
             <div class="portfolio-thumb">
               <img src="img/pexels-maksim-goncharenok-4424216.jpg" class="img-responsive" alt="Portfolio"/>
             </div>
             <div class="detail">
               <h2>H&M</h2>
              <strong>short</strong>
              <span>Lorem, ipsum dolor sit amet consectetur.</span>
<h4>$30.78</h4>
               <a href="#"><i class="fas fa-shopping-cart"></i></a>
               <a href="#"><i class="fas fa-heart"></i></a>
            </div>
            </div>

             </li>

             <li data-category="" data-price="">
               <div class="iso-box col-md-4 col-sm-6">
           <div class="portfolio-thumb">
             <img src="img/pexels-cottonbro-10433903.jpg" class="img-responsive" alt="Portfolio"/>
           </div>
           <div class="detail">
             <h2>ZARA</h2>
            <strong>mediam</strong>
            <span>Lorem, ipsum dolor sit amet consectetur.</span>
<h4>$100.78</h4>
             <a href="#"><i class="fas fa-shopping-cart"></i></a>
             <a href="#"><i class="fas fa-heart"></i></a>
             </div>
          </div>

           </li>

           <li data-category="" data-price="">
             <div class="iso-box col-md-4 col-sm-6">
         <div class="portfolio-thumb">
           <img src="img/pexels-eko-agalarov-10579860.jpg" class="img-responsive" alt="Portfolio"/>
         </div>
         <div class="detail">
           <h2>Dior</h2>
          <strong>mediam</strong>
          <span>Lorem, ipsum dolor sit amet consectetur.</span>
<h4>$160.78</h4>
           <a href="#"><i class="fas fa-shopping-cart"></i></a>
           <a href="#"><i class="fas fa-heart"></i></a>
           </div>
        </div>

         </li>

         <li data-category="" data-price="">
           <div class="iso-box col-md-4 col-sm-6">
       <div class="portfolio-thumb">
         <img src="img/dress.jpg" class="img-responsive" alt="Portfolio"/>
       </div>
       <div class="detail">
         <h2>max</h2>
        <strong>long</strong>
        <span>Lorem, ipsum dolor sit amet consectetur.</span>
 <h4>$43.78</h4>
         <a href="#"><i class="fas fa-shopping-cart"></i></a>
         <a href="#"><i class="fas fa-heart"></i></a>
         </div>
      </div>

       </li>

       <li data-category="" data-price="">
         <div class="iso-box col-md-4 col-sm-6">
     <div class="portfolio-thumb">
       <img src="img/pexels-eyup-beyhan-8517815.jpg" class="img-responsive" alt="Portfolio"/>
     </div>
     <div class="detail">
       <h2>fendy</h2>
      <strong>short</strong>
      <span>Lorem, ipsum dolor sit amet consectetur.</span>
<h4>$700.78</h4>
       <a href="#"><i class="fas fa-shopping-cart"></i></a>
       <a href="#"><i class="fas fa-heart"></i></a>
       </div>
    </div>



     </li>
             </ul>
             </div>
      </div>
              </div>
            </div>
 </div>
</div>
</section>




<!-- Footer section
================================================== -->
<?php include"footer.php"; ?>

<!-- Javascript
 ================================================== -->
 <script src="js/search.js"></script>
 <script type="text/javascript" src="js/main.js"></script>
</body>
</html>

كود JavaScript

(function() {

		let field = document.querySelector('.items');
		let li = Array.from(field.children);

		function FilterProduct() {
			for(let i of li){
				const name = i.querySelector('strong');
				const x = name.textContent;
				i.setAttribute("data-category", x);
			}

			let indicator = document.querySelector('.indicator').children;

			this.run = function() {
				for(let i=0; i<indicator.length; i++)
				{
					indicator[i].onclick = function () {
						for(let x=0; x<indicator.length; x++)
						{
							indicator[x].classList.remove('active');
						}
						this.classList.add('active');
						const displayItems = this.getAttribute('data-filter');

						for(let z=0; z<li.length; z++)
						{
							li[z].style.transform = "scale(0)";
							setTimeout(()=>{
								li[z].style.display = "none";
							}, 500);

							if ((li[z].getAttribute('data-category') == displayItems) || displayItems == "all")
							 {
							 	li[z].style.transform = "scale(1)";
							 	setTimeout(()=>{
									li[z].style.display = "block";
								}, 500);
							 }
						}
					};
				}
			}
		}

		function SortProduct() {
			let select = document.getElementById('select');
			let ar = [];
			for(let i of li){
				const last = i.lastElementChild;
				const x = last.textContent.trim();
				const y = Number(x.substring(1));
				i.setAttribute("data-price", y);
				ar.push(i);
			}
			this.run = ()=>{
				addevent();
			}
			function addevent(){
				select.onchange = sortingValue;
			}
			function sortingValue(){

				if (this.value === 'Default') {
					while (field.firstChild) {field.removeChild(field.firstChild);}
					field.append(...ar);
				}
				if (this.value === 'LowToHigh') {
					SortElem(field, li, true)
				}
				if (this.value === 'HighToLow') {
					SortElem(field, li, false)
				}
			}
			function SortElem(field,li, asc){
				let  dm, sortli;
				dm = asc ? 1 : -1;
				sortli = li.sort((a, b)=>{
					const ax = a.getAttribute('data-price');
					const bx = b.getAttribute('data-price');
					return ax > bx ? (1*dm) : (-1*dm);
				});
				 while (field.firstChild) {field.removeChild(field.firstChild);}
				 field.append(...sortli);
			}
		}

		new FilterProduct().run();
		new SortProduct().run();
	})();

 

تم التعديل في بواسطة سامح أشرف
توضيع عنوان السؤال
رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1

يوجد خطأين في الكود، الخطأ الأول هو عملية تحويل السعر إلى رقم وإضافة الرقم إلى الخاصية data-price، حيث بعد تحديد طريقة ترتيب المنتجات ستجد أن الخاصية data-price تحمل القيمة NaN أي ليس رقم Not a Number وذلك لأنك تقوم بتحويل محتوى العنصر li نفسه إلى رقم من خلال الكائن Number ولكن هذه العملية تفشل لأن محتوى العنصر li ليس رقم بل مجموعة من النصوص، لذلك عليك أن تقوم بتحديد محتوى العنصر h4 الموجود داخل المنتجات بالشكل التالي:

let select = document.getElementById('select');
let ar = [];
for (let i of li) {
    const last = i.lastElementChild.querySelector('h4'); // محدد العنصر h4 
    const x = last.textContent.trim();	// نستخرج السعر كـنص
    const y = Number(x.substring(1));	// نزيل علامة الدولار $ ليتبقى فقط الرقم ونحوله عبر الكائن Number
    i.setAttribute("data-price", y);
    console.log(y);
    ar.push(i);
}

أما الخطأ الثاني يحدث عندما تقوم بجلب قيمة الخاصية data-price من خلال التابع getAttribute، حيث أن الخواص في HTML يتم تخزين القيم فيه على شكل نصوص وليس أرقام Numbers لذلك يعيد التابع getAttribute السعر على شكل نص وبالتالي تتم عملية مقارنة الأسعار لترتيبها بالشكل التالي:

"100.78" > "50.78"	// false

ولحل هذه المشكلة عليك أن تقوم بتحويل السعر إلى رقم مرة أخرى بالشكل التالي:

sortli = li.sort((a, b) => {
    const ax = Number(a.getAttribute('data-price'));
    const bx = Number(b.getAttribute('data-price'));
    return ax > bx ? (1 * dm) : (-1 * dm);
});

بهذا الشكل سوف يتم ترتيب العناصر بشكل سليم حسب السعر.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...