Onclick函数的添加和减去

时间:2018-08-27 12:24:55

标签: javascript jquery html

我正在寻找一种方法来反转onclick函数。

这是功能

var theTotal = 0;


$('button').click(function(){
    theTotal = Number(theTotal) + Number($(this).val());
     $('.total').text(theTotal);    
});

$('.total').text(theTotal); 

现在,它会在Div onclick内添加一个值,但再次单击该值时,应减去相同的值。我该怎么做呢?这是div:

<button class="grid__col--12 border-radius background--white box--shadow padding--medium margin-top--medium margin-top__sm" value="20">
<div class="grid__collapse">
    <div class="grid__col--8 grid__col--sm-12 text--left">
        <strong>
            <h6 class="module">Reserveringsmodule</h6>
        </strong>
    </div>
    <div class="grid__col--4 grid__col--sm-12 text--right color--pink">
        <p class="module">€20 per maand</p>
    </div>
    <div class="grid__col--12 text--left margin-top">
        <p class="module">Mauris non tempor quam, et lacinia sapien. Mauris accumsan eros eget libero posuere vulputate. Etiam elit elit,
            elementum sed varius at, adipiscing vitae est. Sed nec felis pellentesque, lacinia dui sed, ultricies sapien.
            Pellentesque orci lectus, consectetur vel posuere posuere, rutrum eu ipsum.</p>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

为每个按钮使用自定义属性,保存对该按钮的最后一次操作:

data-operation属性添加到元素:

<button data-operation="subtract" value="20">

然后是jQuery;

 var theTotal = 0;

 $('button').click(function(){
     if($(this).data('operation') == "subtract"){
        theTotal = Number(theTotal) + Number($(this).val());
        $(this).data('operation', 'add');
     }else{
        theTotal = Number(theTotal) - Number($(this).val());
        $(this).data('operation', 'subtract');
     }
      $('.total').text(theTotal);    
  });