DOM操作选择元素的方法很多,可以通过CSS选择器来选择
如:1. 通过id
2.通过class
3.通过标签
4.还可以通过name属性
等等,
做了一个同步显示form表单输入的内容小案例,来练习一下DOM的基本操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
h3 {text-align: center;}
.form {width: 200px; height: 150px; border: 1px solid #ccc; margin: 20px auto;}
input {width: 200px; height: 50px;}
table {width: 420px; margin: 20px auto;}
table tr, th, td{border: 1px solid #ccc;}
p {text-align: center;}
</style>
</head>
<body>
<h3>请输入:</h3>
<div class="form">
<form action="">
<input type="text" id="name" placeholder="请输入物品名称" onkeyup="showName()">
<input type="text" id="price" placeholder="请输入物品单价" onkeyup="showPrice()">
<input type="text" id="num" placeholder="请输入物品数量" onkeyup="showNum()">
</form>
</div>
<h3>您输入的信息如下:</h3>
<hr>
<table>
<thead>
<tr>
<th>品名</th>
<th>单价</th>
<th>数量</th>
<th>合计</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name"></td>
<td class="price"></td>
<td class="num"></td>
<td class="total"></td>
</tr>
</tbody>
</table>
<p>总计:</p>
<script>
//同步显示品名
function showName(){
var input = document.getElementById('name');
var td = document.getElementsByClassName('name')[0];
td.innerHTML = input.value;
}
//同步显示单价
function showPrice(){
var input = document.getElementById('price');
var td = document.getElementsByClassName('price')[0];
td.innerHTML = input.value;
}
//同步显示数量
function showNum(){
var input = document.getElementById('num');
var td = document.getElementsByClassName('num')[0];
td.innerHTML = input.value;
//计算合计金额
var price = document.getElementById('price').value;
var num = document.getElementById('num').value;
var total = price*num;
var td = document.getElementsByClassName('total')[0];
td.innerHTML = total+'元';
//计算总合计金额
var a = document.getElementsByTagName('p')[0];
a.innerHTML = '总共'+total+'元';
}
</script>
</body>
</html>