您的位置:首页 > Web前端 > JavaScript

javascript之dom编程(3):常用对象2

2015-11-25 15:27 681 查看
一: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: