输入框中的值不会递增或递减?

时间:2018-02-24 07:09:47

标签: javascript html

我已经制作了两个按钮,一个用于增量,另一个用于递减但是当我单击按钮+它不会增加输入框的值时类似地它不会减少点击按钮上输入框的值 -

main.js:

var currentvalue = document.getElementById("date").value;

console.log(currentvalue);


function increment () {
  var newvalue = parseInt(currentvalue) + 1;
  document.getElementById("date").value = newvalue;
}

function decrement () {
  var newvalue = parseInt(currentvalue) - 1;
  document.getElementById("date").value = newvalue;
}

的index.html:

<body>

    <div id="center">
        <label for="name">Date</label>
        <p></p>
        <button type="button" class="btn btn-success" id="plus" onclick="increment()">+</button>
        <input type="text" id="date" value="1">
        <button type="button" class="btn btn-danger" id="minus" onclick="decrement()">-</button>

    </div>

<script type="text/javascript" src="main.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

截图:

enter image description here

1 个答案:

答案 0 :(得分:2)

将此var currentvalue = document.getElementById("date").value;放在函数内部,因为外部函数在加载过程中只执行一次,然后在其中设置值

&#13;
&#13;
function increment() {
  var currentvalue = document.getElementById("date").value;
  var newvalue = parseInt(currentvalue) + 1;
  document.getElementById("date").value = newvalue;
}

function decrement() {
  var currentvalue = document.getElementById("date").value;
  var newvalue = parseInt(currentvalue) - 1;
  document.getElementById("date").value = newvalue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="center">
  <label for="name">Date</label>
  <p></p>
  <button type="button" class="btn btn-success" id="plus" onclick="increment()">+</button>
  <input type="text" id="date" value="1">
  <button type="button" class="btn btn-danger" id="minus" onclick="decrement()">-</button>

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