思路:
根据点击运算符进行相关的运算。
1、获取点击的运算符;
2、通过节点关系找到input的值;
3、进行运算;
4、将计算后的值返回给本身
JavaScript方式:
<body> <button οnclick="calculate(this)">-</button> <input type="text" size="2" value="1" name="num"> <button οnclick="calculate(this)">+</button><br/> <button οnclick="calculate(this)">-</button> <input type="text" size="2" value="1" name="num"> <button οnclick="calculate(this)">+</button> <script> function calculate(ob){ var opera = ob.innerHTML; if(opera == '+'){ // console.log(ob.previousSibling.previousSibling); var input = ob.previousSibling.previousSibling; input.value = parseInt(input.value) + 1; }else if(opera == '-'){ var input = ob.nextSibling.nextSibling; input.value = parseInt(input.value) - 1; if( input.value < 1 ){ input.value = 1; } } } </script> </body>
jQuery方式:
<body> <button>-</button> <input type="text" size="2" value="1" name="num"> <button>+</button><br/> <button>-</button> <input type="text" size="2" value="1" name="num"> <button>+</button><br/> <script> $(function(){ $('button').on('click',function(){ var opera = $(this).text(); // console.log(opera); if(opera == '+'){ var num = $(this).prev(); num.val( parseInt( num.val() ) + 1 ); // console.log(num.val()); }else if(opera == '-'){ var num = $(this).next(); num.val( parseInt( num.val() ) - 1 ); if(num.val() < 1){ // console.log(num.val()); num.val(1); } } }); }); </script> </body>