京东前端笔试编程题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户名验证</title>
</head>
<body>
<table border="1" cellspacing="0px" cellpadding="10px">
<thead>
<tr>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr>
<td>产品1</td>
<td>10.00</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>产品2</td>
<td>30.20</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>产品1</td>
<td>20.50</td>
<td><a href="javascript:;">删除</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>总计</td>
<td colspan="2">60.70(3件商品)</td>
</tr>
</tfoot>
</table>
</body>
<script>
//add 功能 items 为{name:string,price:number}组成的数组
function add(items){
var len = items.length;
for(var i=0;i<len;i++){
var tr = document.createElement('tr');
tr.innerHTML= '<td>' + items[i].name + '</td><td>'
+ items[i].price.toFixed(2) +
'</td><td><a href="javascript:void(0);">删除</a></td>';
document.getElementsByTagName('tbody')[0].appendChild(tr);
}
changePrice();
}
//delete 功能
function bind(){
var tbody=document.getElementsByTagName('tbody')[0];
tbody.onclick = function(event){
var target = event.target || event.srcElement;
if(target.innerHTML=="删除"){
target.parentElement.parentElement.remove();
changePrice();
}
}
}
function changePrice(){
var tbody = document.getElementsByTagName('tbody')[0];
var trList = tbody.children;
var total = 0;
for(var j=0;j<trList.length;j++){
total += parseFloat(trList[j].children[1].innerHTML);
}
console.log(total,"jaja");
document.getElementsByTagName('tfoot')[0].children[0].children[1].innerHTML = total.toFixed(2)+"("+trList.length+'件商品)';
}
</script> </html>
这道题考察的知识点有:dom结构的增删改查、事件委托机制、数值类型的转化(parseFloat 、toFixed(num)、+可能表示是取正的意思 typeof +"123" //"number")