是否可以将percentDiscount作为参数传递?

时间:2010-11-18 09:12:01

标签: javascript jquery

如果我有这个:

var percentDiscount;

function calculate(sale, original) {

percentDiscount = Math.round(eval(((original-sale)/original) * 100));

    return percentDiscount;
}

$(document).ready(function() {

var salecost;
var originalcost;
var percent;
$('.product').each(function() {

    salecost = $(this).find('.price').html();
    salecost = salecost.replace(/[^\d\.]/g, "");


    originalcost = $(this).find('.actualprice').html();
    if(originalcost == null) return;
    originalcost = originalcost.replace(/[^\d\.]/g, "");

    percentDiscount = calculate(salecost, originalcost);

   if (69 < percentDiscount && percentDiscount < 101) {

        $(this).find("#percentoff").html('&gt; 70% off');
        $(this).find("#percentoff").addClass('badge70');
    }

    else if (49 < percentDiscount && percentDiscount < 70) {

        $(this).find("#percentoff").html('&gt; 50% off');
        $(this).find("#percentoff").addClass('badge50');
    }

    else if (29 < percentDiscount && percentDiscount < 50) {

        $(this).find("#percentoff").html('&gt; 30% off');
        $(this).find("#percentoff").addClass('badge30');
    }


    else if (19 < percentDiscount && percentDiscount < 30) {

        $(this).find("#percentoff").html('&gt; 20% off');
        $(this).find("#percentoff").addClass('badge30');
    }


});
});

是否可以通过percentDiscount以便我可以对页面上的折扣进行排序?例如,按%折扣排序:[全部] [20%] [30%] [50%] [70%]然后匹配每个项目的计算以通过折扣显示?

如果可能的话,请举例说明它应该如何编码或排序?我搜索了可能的答案但没有用。我所看到的最多的是xxx.sort(),但它对百分比折扣不起作用......

另一个问题 - 我想知道如何通过应用于网址的链接进行排序以匹配百分比折扣。那么如何跳过未售出的物品?

1 个答案:

答案 0 :(得分:1)

我会这样试试:

// create an array of dom elements - this assumes a structure like :
// <div class='myStuff'>
//   <span class='product'></span>
//   <span class='product'></span>
// </div>
// and the spans get sorted inside the .myStuff div

var products = [];
$(".product").each(function(){
  products.push(this);
});

products.sort(function(left,right){
  //get left percentDiscount
  //get right percentDiscount

  if(leftDiscount < rightDiscount)
     return -1;
  if(leftDiscount > rightDiscount)
     return 1;
  return 0;
});

// then clear the original .products from .myStuff div and re-add them from the products array.

对于//得左百分比:

salecost = $(left).find('.price').html();
salecost = salecost.replace(/[^\d\.]/g, "");


originalcost = $(left).find('.actualprice').html();
if(originalcost == null) return;
originalcost = originalcost.replace(/[^\d\.]/g, "");

percentDiscount = calculate(salecost, originalcost);

和右边相同 - 这些只是html元素。