js第三十一天

購物車

tr表示行

td表示列 th可以加粗顯示

<table border="1" cellspacing="0" width="500">
<thead>
<tr>
<th>商品名稱</th>
<th>單價(jià)</th>
<th>數(shù)量</th>
<th>小計(jì)</th>
</tr>
</thead>
<tbody>
<tr>
<td>iphone</td>
<td>¥5999</td>
<td>
<button onclick="calc(this)">+</button>
<span>1</span>
<button onclick="calc(this)">-</button>
</td>
<td>¥5999</td>
</tr>
<tr>
<td>iphone</td>
<td>¥5999</td>
<td>
<button onclick="calc(this)">+</button>
<span>1</span>
<button onclick="calc(this)">-</button>
</td>
<td>¥5999</td>
</tr>
<tr>
<td>iphone</td>
<td>¥5999</td>
<td>
<button onclick="calc(this)">+</button>
<span>1</span>
<button onclick="calc(this)">-</button>
</td>
<td>¥5999</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">總計(jì)</td>
<td>¥17997</td>
</tr>
</tfoot>
</table>
<script>
跨列colspan

跨行rowspan

function calc(btn){
//讓n加1或減1通過btn的父元素找到span元素
var span=btn.parentElement
.querySelector("span");
//保存在變量span中獲取span的內(nèi)容保存在變量n中
var n=parseInt(span.innerHTML);
console.log(typeof(n));
//如果btn的內(nèi)容是"+",就讓n+1否則如果n>1,就n--,否則n=1
if(btn.innerHTML=="+"){
n++;
}else if(n>1){
n--
}else{
n=1
}
設(shè)置span的內(nèi)容為n

span.innerHTML=n;
第二步讓每行的小計(jì)變化

找到btn的父元素的前一個(gè)兄弟元素的內(nèi)容

并截取出數(shù)字保存在變量price中

var price=btn.parentElement
.previousElementSibling
.innerHTML
.slice(1);
//聲明subtotal表示小計(jì),subtotal=pricen
var subtotal=price
n;
//找到btn的父元素的下一個(gè)兄弟元素并設(shè)置
// 內(nèi)容為"¥"+subtotal.toFixed(2)
btn.parentElement
.nextElementSibling
.innerHTML="¥"+subtotal
.toFixed(2);
計(jì)算總價(jià)

獲取tbody中每行最后一個(gè)td保存在tds中

var tds=document.querySelectorAll('tbody>tr>td:last-child');
console.log(tds);
for(var i=0,total=0;i<tds.length;i++){
total+=parseFloat(tds[i].innerHTML.slice(1));

}

document.querySelector('tfoot>tr>td:last-child').innerHTML='¥'+total.toFixed(2);

}
</script>
</body>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容