使用 jQuery 中的复选框来切换 2 个数值

Use checkbox in jQuery to toggle 2 numeric values

当检查和未选中复选框时,我将如何更改以下代码在非零值和零值之间切换?参见

$(document).ready(function() {
  $('input[type="checkbox"]').click(function() {
    var inputValue = $(this).attr("value");
    $("." + inputValue).toggle();
  });
});
.box {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label><input type="checkbox" name="colorCheckbox" value="n1"> num 1</label>
  <label><input type="checkbox" name="colorCheckbox" value="n2"> num 2</label>
  <label><input type="checkbox" name="colorCheckbox" value="n3"> num 3</label>
</div>
<div class="n1 box">55000</div>
<div class="n2 box">200</div>
<div class="n3 box">300</div>

https://jsfiddle.net/hcanning/53ye8wf7/

您可以这样做,获取每个复选框的总和,根据需要进行调整

$(document).ready(function() {
var sum = 0;
  $('input[type="checkbox"]').change(function() {
    var inputValue = $(this).attr("value");

   if(this.checked) {
       sum = parseInt(sum) + parseInt($("." + inputValue).text());
   }else {
       sum = parseInt(sum) - parseInt($("." + inputValue).text());
    }
    $("#sum").text(sum);

    $("." + inputValue).toggle();
  });
});
.box {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   


<table width="100%">
<tr> 
<td> <label><input type="checkbox" name="colorCheckbox" value="n1"> Show Price</label></td><td><div class="n1 box">55000</div></td>
</tr><tr> 
<td> <label><input type="checkbox" name="colorCheckbox" value="n2"> Show Price</label></td><td><div class="n2 box">200</div></td>
</tr><tr> 
<td> <label><input type="checkbox" name="colorCheckbox" value="n3"> Show Price</label></td><td><div class="n3 box">300</div></td>
</tr>

<tr> 
<td > Total: </td><td><div id="sum">0</div></td>
</tr>