Jquery将变量推送到数组中

时间:2016-11-27 18:19:48

标签: javascript jquery twitter-bootstrap

我有2个单独的代码,需要将它们组合在一起工作,一个是3个滑块,您可以根据所选值选择不同的值并获得价格。其他代码需要将这些值添加到数组中。目前,ram,diskspace和cpu值以硬编码方式填充,但我需要它来获取滑块的值并使用它。滑块值保存为自己的值,但我不知道如何使它们一起工作。这就是我目前购买的价值插入的购物车:

$(".add-to-cart").click(function(event){
    event.preventDefault(); // prevents the links from doing their default behaviour
    var name = $(this).attr("data-name");
    var price =  Number($(this).attr("data-price")); //so this needs to be the totalPrice from the sliders fiddle
    var ram = Number($(this).attr("data-ram"));// this needs to be the ram from the sliders fiddle
    var diskSpace =Number($(this).attr("data-diskSpace"));// this needs to be the diskSpace from the sliders fiddle
    var cpu = Number($(this).attr("data-cpu"));// this needs to be the cpu from the sliders fiddle
    addItemToCart(name,price,1,ram,diskSpace,cpu);
    displayCart();
});



var cart = [];
var Item = function (name,price,quantity,ram,diskSpace,cpu){
    this.name = name;
    this.price = price;
    this.quantity = quantity;
    this.ram = ram;
    this.diskSpace = diskSpace;
    this.cpu = cpu;
};

//addItemToCart(name,price,quantity)

function addItemToCart(name,price,quantity,ram,diskSpace,cpu){
for (var i in cart){
    if(cart[i].name === name){
        cart[i].quantity +=quantity;
        saveCart();
        return;
    }

}
    var item = new Item(name,price,quantity,ram,diskSpace,cpu);
    cart.push(item);

}

滑块功能:

<div class="wrapper">
  <input class="slider" id="ram" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="10" data-slider-step="1" />
      <hr />

  <input class="slider" id="diskSpace" data-slider-id='ex1Slider2' type="text" data-slider-min="0" data-slider-max="100" data-slider-step="10" />
       <hr />
      <input  class="slider" id="cpu" data-slider-id='ex1Slider3' type="text" data-slider-min="0" data-slider-max="4" data-slider-step="1" />

       <hr />



  </div>
  Prijs:
<div id = "prijs">
</div>


 var minSliderValue = $("#ram").data("slider-min");
var maxSliderValue = $("#ram").data("slider-max");

$('#ram').slider({
    value : 0,
    formatter: function(value) {
        return 'RAM: ' + value + 'GB';
    }
});

$('#diskSpace').slider({
    value : 0,
    formatter: function(value) {
        return 'Disk Space: ' + value + 'GB';
    }
});

$('#cpu').slider({
    value : 0,
    formatter: function(value) {
        return 'CPU : ' + value + ' Cores';
    }
});

// If You want to change input text using slider handler
$('.slider').on('slide', function(slider){

  var ram = $("#ram").val();
  var diskSpace = $("#diskSpace").val();
  var cpu = $("#cpu").val();
var totalPrice=(parseFloat(ram)*3.5 + parseFloat(diskSpace)*0.15+ parseFloat(cpu)*6.5).toFixed(2);
  $("#prijs").html(totalPrice);

});

http://jsfiddle.net/4c2m3cup/42/

1 个答案:

答案 0 :(得分:0)

如果这2个代码在同一个文件中,您可以轻松获取以下值:

$("#ram").val();
$("#cpu").val();

如果上面的代码与html包含在同一页面中,我提到的代码也可以。