首页 > 解决方案 > 存储按钮响应

问题描述

我的屏幕上有两个按钮(1 和 2)。我希望能够将单击哪个按钮存储在变量中,并将总分加 5(如果按钮 1)或减 5(如果按钮 2)。如何存储已单击的按钮?

标签: jquery

解决方案


var total = 0

$("#btn1").on("click", function() {
  total = total + 5;
  $("#txt1").val(total);
});

$("#btn2").on("click", function() {
  total = total - 5;
  $("#txt1").val(total);
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1">+5</button>
<button id="btn2">-5</button>

<input type="text" value="0" id="txt1" />

https://jsfiddle.net/pzfh1m05/


推荐阅读