返回数组中的数组

时间:2016-01-26 23:23:24

标签: javascript jquery arrays

我的插件根据其选项中设置的值修改产品价格。当我启动它时,它会扣除我的ID包含在产品价格中的百分比。

首先,这是整个插件的精简版(见其中的评论):

(function($) {
 $.fn.TTprices = function(options) {
  // Default Settings
  //
  var settings = $.extend({
   threshold: 1,
   discount: 40, // Initial Amount
   products: [],
  }, options);

return this.each(function() {
// Variables
 var $this = $(this);
 var $value = $this.contents()[0].textContent;
 var $price = parseFloat($value);
 var $discount = settings.discount;
 var $total = $price - ($price * $discount);
 var $productID = $this.data('product-id');
 var $products = (settings.products);
 var $saleTag = $this.find("span[data-badge='priceline']"); // Sale Tag for new price

 $this.html(function() {
  for (var i = 0; i < $products.length; i++) {

   var item = $products[i];

// The $productID need to be an array (My issue is here)
// 
if (item.id == $productID) { 
    if ($value >= (settings.threshold)) {

     var extraDiscount = item.extraDiscount ? item.extraDiscount : 0; // for calculting discount

     $discount = ($discount + extraDiscount) / 100;
     $total = $price - ($price * $discount);
     $saleTag.html(($discount * 100) + '% OFF');

     return $this.html().replace($value, $total.toFixed(2) + " ");

    }
   }
  }

  $saleTag.empty();
  return $this.html();
 });

});

 };
}(jQuery));

启动插件后,它会为某些ID添加额外折扣。这是我想要返回ID的数组而不只是一个! (我手动添加ID。)下面是我如何调用插件,你可以看到products选项是一个数组。 ID内需要返回一个数组。我怎样才能做到这一点?

$('.price').TTprices({
 discount: 50,
 products: [{
  id: 'a1', // Here should be an array
  extraDiscount: 10
 }, {
  id: 'a2'// Here should be an array
 }, {
  id: 'a3',// Here should be an array
  extraDiscount: 30
 }],
});

基本上它看起来应该是这样的:

$('.price').TTprices({
 discount: 50,
 products: [{
  id: ['a1'],
  extraDiscount: 10
 }, {
  id: ['a1','a2','a3'], // an array
  extraDiscount: 20

 }],
});

Jsfiddle: https://jsfiddle.net/panoply/2cqv9ar7/

1 个答案:

答案 0 :(得分:0)

处理一系列ID:

var itemIds = $products[i].id;

// The $productID need to be an array (My issue is here)
// 
var inArray = false;
for(var j = 0; j < itemIds.length; j++){
    if (itemIds[j] == $productID) { 
        inArray = true;
        break;
    }
}

if (inArray) { 
     ....