標籤:javascript
一:document對象
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<script type="text/javascript">
//document最重要的三個方法
//getElementById [html php jsp] (如果頁面中有多個相同的id,則返回第一個對象引用)
//getElementsByName 通過html控制項的名字返回對象集合 多用於多選。
//getElementsByTagName 通過html的標籤名返回對象集合
//1.id擷取對象
function test(){
var a1=document.getElementById("a1");
window.alert(a1.id+" "+a1.href+" "+a1.innerText);
}
//2.通過name擷取對象
function test2(){
var hobies=document.getElementsByName("hobby");
//遍曆這個集合
for(var i=0;i<hobies.length;i++){
if(hobies[i].checked){
window.alert("你的愛好是:"+hobies[i].value);
}
}
}
//3.通過標籤名擷取對象
function test3(){
var input=document.getElementsByTagName("input");
window.alert(input.length);
}
</script>
<body>
<a id="a1" href="http://www.sina.com">串連到sina</a><br/>
<a id="a1" href="http://www.sohu.com">串連到sohu</a><br/>
<a id="a3" href="http://www.baidu.com">串連到baidu</a><br/>
<input type="button" value="測試" onclick="test()"/><br/>
請選擇你的愛好:
<input type="checkbox" name="hobby" value="旅遊">旅遊
<input type="checkbox" name="hobby" value="音樂">音樂
<input type="checkbox" name="hobby" value="體育">體育
<input type="checkbox" name="hobby" value="電影">電影
<input type="button" value="看看你的愛好" onclick="test2()"/><br/>
<input type="button" value="通過tagname來擷取元素" onclick="test3()"/><br/>
</body>
<hr>
</body>
</html>
二:綜合案例,動作節點
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<script type="text/javascript">
//綜合案例
/*
createElement() 方法建立新的元素節點:
appendChild() 方法向已存在的節點添加子節點。
removeChild() 方法刪除指定的節點。
parentNode 屬性可返回某節點的父節點。
*/
function test4(){
var myhref=document.createElement("a");
myhref.innerText="串連到sina";
myhref.href="http://www.baidu.com";
myhref.id="myhref";
div1.appendChild(myhref);
}
function test5(){
var node=document.getElementById(‘myhref‘);
node.parentNode.removeChild(node);
}
</script>
<body>
<input type="button" value="建立一個a標籤" onclick="test4()"/><br/>
<input type="button" value="刪除一個a標籤" onclick="test5()"/><br/>
<div id="div1" style="width:200px;height:200px;background-color:green">div1</div>
</body>
<hr>
</body>
</html>
三:查詢鍵盤編碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<script type="text/javascript">
function test(){
window.alert("你按下鍵的編碼:"+window.event.keyCode);
}
</script>
<body>
<input type="button" onkeydown="test()" value="tesing"/>
</body>
<hr>
</body>
</html>
著作權聲明:博主原創文章,轉載請說明出處。http://blog.csdn.net/dzy21
javascript之dom編程(3):常用對象2