从数组中获取最后一次单击项的值

时间:2015-12-08 21:07:26

标签: javascript jquery arrays if-statement for-loop

更新#2:更新了脚本。

目标

a)用户选择一个按钮。点击最后一个按钮的值+ .current__amount = new__amount

b)没有总计。再次点击同一按钮应该取消选中它,然后从.new__amount中减去该值,然后使用.html()更改占位符文字

问题

是的,现在无论出于何种原因,点按按钮都不会在.new__amount中添加或删除其值。

console.log(buttons[i].value)console.log(buttons[i].class)并且可以看到for循环正在打印类和这六个按钮的值,这些按钮表示无声拍卖中的出价{{1}并且已经存储在名为$10, 25, 50的数组中,就像我想要的那样。

scripts.js(已更新)

几乎就在那里。只需要做到这一点,一次只能选择一个按钮。

var buttons = []

1 个答案:

答案 0 :(得分:1)

这不是特定于您的问题结构,但它应该让您了解它是如何工作的。

$(document).ready(function() {
  var totalAmount = 0;
  $('.button__form').on('click', function() {
    var value = $(this).val();
    if($(this).hasClass('selected')) {
      $(this).removeClass('selected');
      totalAmount = parseInt(totalAmount) - parseInt(value);
    }
    else {
      $(this).addClass('selected');
      totalAmount = parseInt(totalAmount) + parseInt(value);
    }    
    $('.total').html(totalAmount);
  });
});
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button__form" value=10>10</button>
<button class="button__form" value=25>25</button>
<button class="button__form" value=50>50</button>
<button class="button__form" value=100>100</button>
<button class="button__form" value=250>250</button>
<button class="button__form" value=500>500</button>
<br/><br/>
<div class="total"><div>

编辑,一次只能选择一个按钮:

$(document).ready(function() {
  var baseAmount = 0;
  var totalAmount = baseAmount;
  $('.button__form').on('click', function() {
    var value = $(this).val();
    if($(this).hasClass('selected')) {
      $(this).removeClass('selected');
      totalAmount = parseInt(totalAmount) - parseInt(value);
    }
    else {
      $('.button__form').removeClass('selected'); // remove selected css from all the other buttons
      $(this).addClass('selected');
      totalAmount = baseAmount; // reset the totalAmount to the original base amount
      totalAmount = parseInt(totalAmount) + parseInt(value);
    }    
    $('.total').html(totalAmount);
  });
});
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button__form" value=10>10</button>
<button class="button__form" value=25>25</button>
<button class="button__form" value=50>50</button>
<button class="button__form" value=100>100</button>
<button class="button__form" value=250>250</button>
<button class="button__form" value=500>500</button>
<br/><br/>
<div class="total"><div>