jQuery中动态按钮的加减功能

时间:2017-02-16 11:07:58

标签: javascript jquery

inputbutton动态时,如何在添加或删除项目数量时单独设置input值?

目前,如果我更改项目的数量,它会更新我不想发生的所有输入。只想更新我点击的项目的数量值。

var drinks = data.categories.drinks;
        $.each(drinks, function (index, value) {
            $('#drink_list').append(
                '<div class="col-sm-4"> <div class="thumbnail">' +
                '<img src="./assets/imgs/' + value.image + '" alt="..."> <div class="caption">' +
                '<p>' + value.name + ' ' + value.liter + '<span class="pull-right">£' + value.price + '</span></p>' +
                '<p>' + '<button id="qButtonMinus" onclick="minus()">-</button> <input type="text" name="quantity" style="width:30px;" class="value"> <button onclick="add()" id="qButtonAdd">+</button>' +
                '<button class="btn btn-success btn-sm pull-right" onClick="addToCart(\'' + value.name + '\',\'' + value.price + '\')"> Add </button>' + '</p>' +
                '</div> </div> </div>'
            );
        })

add = function () {
    currentQuantity++;
    $('.value').val(currentQuantity)
    console.log('Add > ', currentQuantity)
}

minus = function () {
    if (currentQuantity > 0) {
        currentQuantity--;
    }
    $('.value').val(currentQuantity);
    console.log('Minus > ', currentQuantity)
}

Sample

3 个答案:

答案 0 :(得分:2)

我更改了以下代码:

add = function(obj) {
  var count = $(obj).siblings('input').val();

  $(obj).siblings('input').val(parseInt(++count))
  var at = $(obj).siblings('button.addToCard');
  var valcount = at.attr("onClick").split(',');
  at.attr("onClick", valcount[0] + "," + valcount[1] + "," + count + ")")
}

minus = function(obj) {
  var count = $(obj).siblings('input').val();

  if (count > 0) {
    $(obj).siblings('input').val(parseInt(count - 1))
    var at = $(obj).siblings('button.addToCard');
    var valcount = at.attr("onClick").split(',');
    at.attr("onClick", valcount[0] + "," + valcount[1] + "," + parseInt(count - 1) + ")")

  }
}

现在你必须将一个对象传递给函数:onclick="minus(this)" this获取你点击的对象

更新btn功能现在看起来像btn = function(item, price, itemCount)

运行代码,它应该可以正常工作

&#13;
&#13;
var json = {
  "categories": {
    "drinks": [{
      "id": "1",
      "name": "Coke",
      "liter": "500ml",
      "price": 1.99,
      "image": ""
    }, {
      "id": "2",
      "name": "Coke Diet",
      "liter": "500ml",
      "price": 1.99,
      "image": "/products/dietcoke-medium.png"
    }, {
      "id": "3",
      "name": "Sprite",
      "liter": "500ml",
      "price": 1.99,
      "image": "/products/sprite-medium.png"
    }, {
      "id": "4",
      "name": "Powerrade",
      "liter": "",
      "price": 3.59,
      "image": "/products/powerade-medium.png"
    }, {
      "id": "5",
      "name": "Pure Life Water",
      "liter": "",
      "price": 1.49,
      "image": "/products/Pure-medium.png"
    }, {
      "id": "6",
      "name": "Refillable Mug",
      "liter": "",
      "price": 2.99,
      "image": "/products/Home-medium.png"
    }],
    "clothes": [{}]
  }
};
var cartItemArr = [];
var cartPriceArr = [];
var currentQuantity = 0;
var allItems = json.categories.drinks;
$.each(allItems, function(index, value) {
  $('#items').append(
    '<div class="col-sm-4"> <div class="thumbnail">' +
    '<img src="./assets/imgs/' + value.image + '" alt="..."> <div class="caption">' +
    '<p>' + value.name + ' ' + value.liter + '<span class="pull-right">£' + value.price + '</span></p>' +
    '<p>' + '<button id="qButtonMinus" onclick="minus(this)">-</button> <input type="text" name="quantity" style="width:30px;" class="value"> <button onclick="add(this)" id="qButtonAdd">+</button>' +
    '<button class="btn btn-success btn-sm pull-right addToCard" onClick="addToCart(\'' + value.name + '\',\'' + value.price + '\',0)"> Add </button>' + '</p>' +
    '</div> </div> </div>'
  );
})

add = function(obj) {
  var count = $(obj).siblings('input').val();

  $(obj).siblings('input').val(parseInt(++count))
  var at = $(obj).siblings('button.addToCard');
  var valcount = at.attr("onClick").split(',');
  at.attr("onClick", valcount[0] + "," + valcount[1] + "," + count + ")")
}

minus = function(obj) {
  var count = $(obj).siblings('input').val();

  if (count > 0) {
    $(obj).siblings('input').val(parseInt(count - 1))
    var at = $(obj).siblings('button.addToCard');
    var valcount = at.attr("onClick").split(',');
    at.attr("onClick", valcount[0] + "," + valcount[1] + "," + parseInt(count - 1) + ")")

  }
}


addToCart = function(item, price, itemCount) {
  console.log(itemCount);
  var itemQuantity = {};
  var item_quantity;
  var quantity;

  var increaseQuantity = 0;
  cartItemArr.push(item);
  cartPriceArr.push(price);

  // Sum up all items
  var totalPrice = 0;
  $.each(cartPriceArr, function() {
    totalPrice += parseFloat(this) || 0;
    $('.total').text(totalPrice.toFixed(2));
  });

  // Item quantity count
  for (var i = 0, j = cartItemArr.length; i < j; i++) {
    if (itemQuantity[cartItemArr[i]]) {
      itemQuantity[cartItemArr[i]]++;
    } else {
      itemQuantity[cartItemArr[i]] = 1;
    }
  }

  for (var drink in itemQuantity) {
    quantity = itemQuantity[drink] + "x ";
  }

  // Render items in virtual receipt
  $('.cart').append(
    '<div class="col-sm-6">' + quantity + item +
    '</div>' +
    '<div class="col-sm-6" style="text-align: right;">' + price +
    '</div>'
  );
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3">
  <div class="cart">
    <h3>Cart</h3>
  </div>
</div>
<div class="col-sm-9">
  <div id="items">

  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

点击html点击此onclick="minus(this)"onclick="add(this)"这是Updated Fiddle

add = function (elem) {
  var $main = $(elem).prev();
  var val = $main.val().length ? $main.val() : 0;
  val++;
  $main.val(val);
}

minus = function (elem) {
  var $main = $(elem).next();
  var val = $main.val();
  if(!val.length || val <= 0) return;
  val--;
  $main.val(val);
}

var json = {
  "categories": {
    "drinks": [{
        "id": "1",
        "name": "Coke",
        "liter": "500ml",
        "price": 1.99,
        "image": ""
      },
      {
        "id": "2",
        "name": "Coke Diet",
        "liter": "500ml",
        "price": 1.99,
        "image": "/products/dietcoke-medium.png"
      },
      {
        "id": "3",
        "name": "Sprite",
        "liter": "500ml",
        "price": 1.99,
        "image": "/products/sprite-medium.png"
      },
      {
        "id": "4",
        "name": "Powerrade",
        "liter": "",
        "price": 3.59,
        "image": "/products/powerade-medium.png"
      },
      {
        "id": "5",
        "name": "Pure Life Water",
        "liter": "",
        "price": 1.49,
        "image": "/products/Pure-medium.png"
      },
      {
        "id": "6",
        "name": "Refillable Mug",
        "liter": "",
        "price": 2.99,
        "image": "/products/Home-medium.png"
      }
    ],
    "clothes": [{}]
  }
};
var cartItemArr = [];
var cartPriceArr = [];
var currentQuantity = 0;
var allItems = json.categories.drinks;
$.each(allItems, function(index, value) {
  $('#items').append(
    '<div class="col-sm-4"> <div class="thumbnail">' +
    '<img src="./assets/imgs/' + value.image + '" alt="..."> <div class="caption">' +
    '<p>' + value.name + ' ' + value.liter + '<span class="pull-right">£' + value.price + '</span></p>' +
    '<p>' + '<button id="qButtonMinus" onclick="minus(this)">-</button> <input type="text" name="quantity" style="width:30px;" class="value"> <button onclick="add(this)" id="qButtonAdd">+</button>' +
    '<button class="btn btn-success btn-sm pull-right" onClick="addToCart(\'' + value.name + '\',\'' + value.price + '\')"> Add </button>' + '</p>' +
    '</div> </div> </div>'
  );
})

add = function(elem) {
  var $main = $(elem).prev();
  var val = $main.val().length ? $main.val() : 0;
  val++;
  $main.val(val);
}

minus = function(elem) {
  var $main = $(elem).next();
  var val = $main.val();
  if (!val.length || val <= 0) return;
  val--;
  $main.val(val);
}


btn = function(item, price) {
  var itemQuantity = {};
  var item_quantity;
  var quantity;

  var increaseQuantity = 0;
  cartItemArr.push(item);
  cartPriceArr.push(price);

  // Sum up all items
  var totalPrice = 0;
  $.each(cartPriceArr, function() {
    totalPrice += parseFloat(this) || 0;
    $('.total').text(totalPrice.toFixed(2));
  });

  // Item quantity count
  for (var i = 0, j = cartItemArr.length; i < j; i++) {
    if (itemQuantity[cartItemArr[i]]) {
      itemQuantity[cartItemArr[i]]++;
    } else {
      itemQuantity[cartItemArr[i]] = 1;
    }
  }

  for (var drink in itemQuantity) {
    quantity = itemQuantity[drink] + "x ";
  }

  // Render items in virtual receipt
  $('.cart').append(
    '<div class="col-sm-6">' +
    quantity + item +
    '</div>' +
    '<div class="col-sm-6" style="text-align: right;">' +
    price +
    '</div>'
  );
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3">
  <div class="cart">
    <h3>Cart</h3>
  </div>
</div>
<div class="col-sm-9">
  <div id="items">

  </div>
</div>

答案 2 :(得分:0)

button html更改为

<button onclick="add(this)" id="qButtonAdd">

然后将您的add()方法更改为

add = function (e) {
    currentQuantity++;
    $(e).prev('input').val(currentQuantity)
    console.log('Add > ', currentQuantity)
}

您可以为minus()

应用类似的逻辑