题解 | #购物车#
购物车
http://www.nowcoder.com/practice/3b4a342351ce483e813e5588446fc1f8
add()
function add(items) { //items [{name, price}] //1.获取父节点 var tbody = document.getElementsByTagName('tbody')[0] var tfoot = document.getElementsByTagName('tfoot')[0] //2.获取初始数据 var num = tbody.children.length var total = parseFloat(tfoot.innerText.match(/\d+.\d+/)[0]) // var total = tfoot.innerText.match(/^.*\t(\d*\.?\d*)\(.*\)$/)[1] //3.创建子节点 //产品行 var tr = "" for (let i in items){ total = parseFloat((total+items[i].price).toFixed(2)) tr += ` ${items[i].name} ${items[i].price.toFixed(2)} <a href="javascript:void(0);">删除</a> ` num++ } //总计行 var tf = `总计${total.toFixed(2)}(${num}件商品)` //4.将新增的添加进去 tfoot.innerHTML = tf tbody.innerHTML = tbody.innerHTML+tr }
bind()
正则表达式:/^.\t(\d*.?\d)\t.*$/
console.log(event.target.parentElement.parentElement.innerText.match(/^.*\t(\d*\.?\d*)\t.*$/)); //[0:"产品1\t10.00\t删除", 1:"10.00", index: 0, input: "产品\t10.00\t删除", groups: undefined]
function bind() { //1.获取父节点 var tbody = document.getElementsByTagName('tbody')[0] var tfoot = document.getElementsByTagName('tfoot')[0] //2.添加点击事件 tbody.addEventListener('click',(event)=>{ var num = tbody.children.length if(event.target.tagName == 'A'){ //获取数据 var price = event.target.parentElement.parentElement.innerText.match(/^.*\t(\d*\.?\d*)\t.*$/)[1] var total = parseFloat(tfoot.innerText.match(/\d+.\d+/)[0]) //修改数据 total = parseFloat((total-price).toFixed(2)) var tf = `总计${total.toFixed(2)}(${num-1}件商品)` tfoot.innerHTML = tf //删除节点 event.target.parentElement.parentElement.remove() } }) } //启动bind()监听 bind()