分別用JavaScript,jQuery和vue做了一個簡單的購物車加減按鈕部分。 HTML: css(主要是去除按鈕預設樣式,賦予新樣式): JavaScript: jQuery: vue版 HTML: vue: ...
分別用JavaScript,jQuery和vue做了一個簡單的購物車加減按鈕部分。
HTML:
<ul class="counter"> <li id="minus"><input type="button" onclick="minuser()" value="-"/></li> <li id="countnum">0</li> <li id="plus"><input type="button" onclick="adder()" value="+"/></li> </ul>
css(主要是去除按鈕預設樣式,賦予新樣式):
ul,li{margin:0; padding:0; } .counter li{float:left; list-style-type:none; width:30px; height:30px; text-align:center; line-height:30px; border:#999 thin solid; background-color:#fff} .counter li input{font-size:20px; width:100%; height:100%; outline:none; -webkit-appearance:none; background:none; margin:0; padding:0; border: 1px solid transparent; border-radius: 0;} #countnum{ border-left:hidden; border-right:hidden; color:#666}
JavaScript:
function adder(){ var count=document.getElementById("countnum").innerHTML; count=parseInt(count)+1; document.getElementById("countnum").innerHTML=count; } function minuser(){ var count=document.getElementById("countnum").innerHTML; if(count<=0){ count=0; }else{ count=parseInt(count)-1; } document.getElementById("countnum").innerHTML=count; }
jQuery:
function adder(){ var count=$("#countnum").text(); count=parseInt(count)+1; $("#countnum").text(count); } function minuser(){ var count=$("#countnum").text(); if(count<=0){ count=0; }else{ count=parseInt(count)-1; } $("#countnum").text(count); }
vue版
HTML:
<p>vue版</p> <ul class="counter"> <li id="minus"><input type="button" v-on:click="minuser" value="-"/></li> <li id="countnum" >{{ count }}</li> <li id="plus"><input type="button" v-on:click="adder" value="+"/></li> </ul>
vue:
new Vue({ el: '.counter', data: { count:0 }, methods: { adder: function () { this.count++; }, minuser: function (event) { if(this.count<=0){ this.count=0; }else{ this.count--; } } } });