B/S学习之路—DOM(2)

来源:互联网 发布:数据库分组查询原理 编辑:程序博客网 时间:2024/06/05 14:57

【03获取元素】

代码:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    </head><body>    <input type="button" name="btnShow" id="btnShow" value="显示"/>    <script>        //根据id获取元素,因为id是唯一的,所以只返回一个dom对象        var temp1 = document.getElementById('btnShow');        //name是可以重复的,所以返回一个dom对象数组        var temp2 = document.getElementsByName('btnShow');                //访问属性        temp1.value = '显示当前时间';    </script></body></html>
执行效果:

【04事件】

代码:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>事件</title></head>    <body>        在元素上注册事件        <input type="button" id="btnShow1" value="显示1" onclick="alert(this.value);"/>        <br/>        动态注册:        <input type="button" id="btnShow2" value="显示2"/>        <script>            //推荐使用这种方式注册事件            //好处:实现了代码分离(html与js);可以使用this            document.getElementById('btnShow2').onclick= function() {                alert(this.value);            }        </script>    </body></html>
执行效果:

点击按钮“显示1”,弹出如下对话框:


点击按钮“显示2”,弹出如下对话框:


【05加载完成事件】

代码:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <script>        //页面中的所有节点加载完成后,会触发此事件        onload = function () {            //当节点存在后,找到并注册点击事件            document.getElementById('span1').onclick = function () {                alert('ok');            };        };    </script></head><body>    <span id="span1">点击显示</span></body></html>
执行效果:


点击“点击显示”,出现如下显示:


原创粉丝点击