javascript onclick增量编号

use*_*585 6 javascript numbers onclick

使用javascript,我怎么能这样做,所以当我点击表单按钮时,它会在数字上加1?它递增的数字可以是表单文本字段或其他内容.

显然它会在onclick上,但我不确定代码.

Gab*_*abe 30

既然你没有给我任何开始,这是一个简单的例子.

的jsfiddle

示例实现:

function incrementValue()
{
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}
Run Code Online (Sandbox Code Playgroud)

示例Html

<form>
   <input type="text" id="number" value="0"/>
   <input type="button" onclick="incrementValue()" value="Increment Value" />
</form>
Run Code Online (Sandbox Code Playgroud)

  • user1022585,如果要将相同的函数应用于多个元素,可以将输入id作为参数添加(即`incrementValue(id)`),然后将`getElementById('number')`更改为`getElementById(id)` (2认同)

pai*_*lee 9

在其最基本的化身..

JavaScript的:

<script>
    var i = 0;
    function buttonClick() {
        document.getElementById('inc').value = ++i;
    }
</script>
Run Code Online (Sandbox Code Playgroud)

标记:

<button onclick="buttonClick()">Click Me</button>
<input type="text" id="inc" value="0"></input>
Run Code Online (Sandbox Code Playgroud)

  • @Gabe可能是坏事.但价值永远不是用户输入.这是一个值得投票的问题吗? (2认同)

pse*_*ant 8

jQuery示例

var $button = $('.increment-btn');
var $counter = $('.counter');

$button.click(function(){
  $counter.val( parseInt($counter.val()) + 1 ); // `parseInt` converts the `value` from a string to a number
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="1" class="counter"/>
<button type="button" class="increment-btn">Increment</button>
Run Code Online (Sandbox Code Playgroud)

'普通'JavaScript示例

var $button = document.querySelector('.increment-btn');
var $counter = document.querySelector('.counter');

$button.addEventListener('click', function(){
  $counter.value = parseInt($counter.value) + 1; // `parseInt` converts the `value` from a string to a number
}, false);
Run Code Online (Sandbox Code Playgroud)
<input type="text" class="counter" value="1"/>
<button type="button" class="increment-btn">Increment</button>
Run Code Online (Sandbox Code Playgroud)