javascript开发购物车之函数实现文本框处理
上两节,我们已经把加减的功能完成了,现在我们来对文本框的数量进行处理
文本框正常情况下我们是可以输入的,在这里我们同样也是允许输入的,当我们输入一段字符,或者中文时
我们就应该不执行了,给出提示信息,然后给文本框一个默认值,下面我们来看代码:
<script> function a3(td,td2,id){ var price = document.getElementById(td).innerHTML;//获得单价 var total = document.getElementById(td2).innerHTML;//获得总价 var v1 = parseInt(document.getElementById(id).value);//获得数量 if(isNaN(v1) || v1 < 1){ alert("请输入正确的数字"); document.getElementById(id).value = 1 ; v1 = parseInt(document.getElementById(id).value); }else{ document.getElementById(id).value = v1 ; } document.getElementById(td2).innerHTML = parseInt(price) * parseInt(v1); } </script>
v1 是我们获取的文本框的值,对 v1 进行判断,isNaN()函数检测v1是不是非法的数字,v1<1 则是一个负数,这样的情况,我们都给出一个默认值,然后把这个值赋值给数量
下面展示一下加减功能和处理文本框的完整代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> table{width:350px;border:1px solid #eee;text-align:center;} .tr2{height:50px;} input{width:30px;height:20px;text-align: center;} a{text-decoration:none} </style> <script type="text/javascript"> function a1(td,td2,id){ var price = document.getElementById(td).innerHTML;//获得单价 var total = document.getElementById(td2).innerHTML;//获得总价 var v1 = parseInt(document.getElementById(id).value);//获得数量 document.getElementById(id).value = v1+1; document.getElementById(td2).innerHTML = parseInt(price) * parseInt(v1+1); } function a2(td,td2,id){ var price = document.getElementById(td).innerHTML;//获得单价 var total = document.getElementById(td2).innerHTML;//获得总价 var v1 = parseInt(document.getElementById(id).value);//获得数量 if(v1>1){ document.getElementById(id).value = v1-1; document.getElementById(td2).innerHTML = parseInt(price) * parseInt(v1-1); }else{ var v1 = 1; } } function a3(td,td2,id){ var price = document.getElementById(td).innerHTML;//获得单价 var total = document.getElementById(td2).innerHTML;//获得总价 var v1 = parseInt(document.getElementById(id).value);//获得数量 if(isNaN(v1) || v1 < 1){ alert("请输入正确的数字"); document.getElementById(id).value = 1 ; v1 = parseInt(document.getElementById(id).value); }else{ document.getElementById(id).value = v1 ; } document.getElementById(td2).innerHTML = parseInt(price) * parseInt(v1); } </script> </head> <body> <table cellspacing="0" cellpadding="0" border="1"> <tr> <th>名称</th> <th>单价</th> <th>数量</th> <th>总价</th> </tr> <tr class="tr2"> <td>手表</td> <td id="price">1999</td> <td> <a href="#" id="a1" class="tp1" onclick="a2('price','total','count')">-</a> <input type="text" value="1" id="count" onblur="a3('price','total','count')"> <a href="#" id="a2" class="tp2" onclick="a1('price','total','count')">+</a> </td> <td id="total">1999</td> </tr> <tr class="tr2"> <td>手机</td> <td id="price_1">1999</td> <td> <a href="#" id="a1" class="tp1" onclick="a2('price_1','total_1','count_1')">-</a> <input type="text" value="1" id="count_1" onblur="a3('price_1','total_1','count_1')"> <a href="#" id="a2" class="tp2" onclick="a1('price_1','total_1','count_1')">+</a> </td> <td id="total_1">1999</td> </tr> </table> </br> </body> </html>