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

一: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="测试" οnclick="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="看看你的爱好" οnclick="test2()"/><br/>
<input type="button" value="通过tagname来获取元素" οnclick="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标签" οnclick="test4()"/><br/>
<input type="button" value="删除一个a标签" οnclick="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" οnkeydοwn="test()" value="tesing"/>
</body>
<hr>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值