1 Document对象
Document对象的理解:
- Document它管理了所有的HTML文档内容
- Document它是一种树结构的文档,有层级关系
- 它让我们把所有的标签都对象化
- 可以通过Document访问所有的标签对象
2 验证用户名是否有效
需求:当用户点击了验证按钮,要获取输入框中的内容,然后验证其是否合法(验证规则是:必须由字母、数字、下划线组成,并且长度是5到12位)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getElementById</title>
<script type="text/javascript">
function onclickFun() {
var userNameObj = document.getElementById("userName")
var userNameText = userNameObj.value;
var patt = /^\w{5,12}$/;
if (patt.test(userNameText)) {
alert("用户名合法");
} else {
alert("用户名不合法");
}
}
</script>
</head>
<body>
用户名:<input type="text" id="userName" value="">
<button onclick="onclickFun()">验证</button>
</body>
</html>
3 正则表达式对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>regexp</title>
<script type="text/javascript">
var patt = /a/;
var patt = /[abc]/;
var patt = /[a-z]/;
var patt = /[A-Z]/;
var patt = /[0-9]/;
var patt = /\w/;
var patt = /a+/;
var patt = /a*/;
var patt = /a?/;
var patt = /a{3}/;
var patt = /a{3,4}/;
var patt = /a{3,}/;
var patt = /a$/;
var patt = /^a/;
var patt = /^a{3,4}$/;
var str = "abs";
alert(patt.test(str));
</script>
</head>
<body>
</body>
</html>
更多的正则表达式写法详见:正则表达式详细
4 getElementsByName()方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getElementsByName</title>
<script type="text/javascript">
function checkAll() {
var hobbies = document.getElementsByName("hobby");
for (var i = 0; i < hobbies.length; i++) {
hobbies[i].checked = true;
}
}
function checkNo() {
var hobbies = document.getElementsByName("hobby");
for (var i = 0; i < hobbies.length; i++) {
hobbies[i].checked = false;
}
}
function checkReverse() {
var hobbies = document.getElementsByName("hobby");
for (var i = 0; i < hobbies.length; i++) {
hobbies[i].checked = !hobbies[i].checked;
}
}
</script>
</head>
<body>
兴趣课程:
<input type="checkbox" name="hobby" value="cpp" checked="checked">C++
<input type="checkbox" name="hobby" value="java">java
<input type="checkbox" name="hobby" value="js">javascript
<br/>
<button onclick="checkAll()">全选</button>
<button onclick="checkNo()">全不选</button>
<button onclick="checkReverse()">反选</button>
</body>
</html>
getElementByTagName()方法是按照指定标签名来进行查询并返回集合,它的用法与getElementsByName()方法一致。
|