zoukankan      html  css  js  c++  java
  • 自学_DOM<五>

    类库DOM

    DOM(document object medol)文档对象模型。

    • DOM就是HTML页面的模型,将每个标签都做为一个对象,JavaScript通过调用DOM中的属性、方法就可以对网页中的文本框、层等元素进行编程控制。比如通过操作文本框的DOM对象,就可以读取文本框中的值、设置文本框中的值。
    • JavaScript→Dom就是C#→.Net Framwork。没有.net,C#只能for、while,连WriteLine、MessageBox都不行。Dom就是一些让JavaScript能操作HTML页面控件的类、函数。
      DOM也像WinForm一样,通过事件、属性、方法进行编程。
      CSS+JavaScript+DOM=DHTML
    • 学习阶段只考虑IE。用IE Collection安装IE所有版本,学习使用IE6(要调试必须使用本机安装的版本)。

    事件

    • 事件:<body onmousedown="alert('哈哈')">当点击鼠标的时候执行onmousedown中的代码。有时间事件响应的代码太多,就放到单独的函数中:
    <script type="text/javascript">
    function bodymousedown() {
    alert("网页被点坏了,赔吧!");
    alert("逗你玩的!");
    }
    </script>
    <body onmousedown="bodymousedown()">
    
    • bodymousedown后的括号不能丢( onmousedown="bodymousedown" ),因为表示onmousedown事件发生时调用bodymousedown函数,而不是onmousedown事件的响应函数是bodymousedown。
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function setTxt() {
                t1.value = "1234";
            }
        </script>
    </head>
    <body onload="setTxt();" onunload="alert('欢迎下次光临!')" onbeforeunload="window.event.returnValue='确定关闭?'">
        <input id="t1" type="text" value="" />
    </body>
    </html>
    

    动态设置事件

    可以在代码中动态设置事件响应函数,就像.Net中btn.Click+=一样

    function f1() {
    alert("1");
    }
    function f2(){
    alert("2");
    }
    

    <input type="button" onclick="document.ondblclick=f1" value="关联事件1" />//注意f1不要加括号。如果加上括号就变成了执行f1函数,并且将函数的返回值复制给document.ondblclick
    <input type="button" onclick="document.ondblclick=f2" value="关联事件2" />

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function load() {
                alert('地球日'); 
                
                alert('2012不远了');
            }
            function f1() {
                alert("f1");
            }
            
           
        </script>
    </head>
    <body>
       <input type="button" value="按钮" onclick="document.onclick=f1" />
       <input type="button" value="关闭" onclick="window.close()" />
    </body>
    </html>
    

    window对象

    • window对象代表当前浏览器窗口,使用window对象的属性、方法的时候可以省略window,比如window.alert('a')可以省略成alert('aa')。
      • alert方法,弹出消息对话框
      • confirm方法,显示“确定”、“取消”对话框,如果按了【确定】按钮,就返回true,否则就false
    if (confirm("是否继续?")) {
    alert("确定");
    }
    else {
    alert("取消");
    }
    
    + 重新导航到指定的地址:navigate("http://www.rupeng.com");
    + setInterval每隔一段时间执行指定的代码,第一个参数为代码的字符串,第二个参数为间隔时间(单位毫秒),返回值为定时器的标识
    	`setInterval("alert('hello')", 5000);`
    + clearInterval取消setInterval的定时执行,相当于Timer中的Enabled=False。因为setInterval可以设定多个定时,所以clearInterval要指定清除那个定时器的标识,即setInterval的返回值。
    

    var intervalId = setInterval("alert('hello')", 5000); clearInterval(intervalId);
    + setTimeout也是定时执行,但是不像setInterval那样是重复的定时执行,只执行一次,clearTimeout也是清除定时。很好区分:Interval:间隔;timeout:超时。
    var timeoutId = setTimeout("alert('hello')", 2000);

    + showModalDialog弹出模态对话框,注意showModalDialog必须在onClick等用户手动触发的事件中才会执行,否则可能会被最新版本的浏览器当成广告弹窗而拦截。
    	+ 第一个参数为弹出模态窗口的页面地址。
    	+ 在弹出的页面中调用window.close()(不能省略window.close()中的window.)关闭窗口,只有在对话框中调用window.close()才会自动关闭窗口,否则浏览器会提示用户进行确认。
    + 除了有特有的属性之外,当然还有通用的HTML元素的事件:onclick(单击)、ondblclick(双击)、onkeydown(按键按下)、onkeypress(点击按键)、onkeyup(按键释放)、onmousedown(鼠标按下)、onmousemove(鼠标移动)、onmouseout(鼠标离开元素范围)、onmouseover(鼠标移动到元素范围)、onmouseup(鼠标按键释放)等。
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>1234567890</title>
        <script type="text/javascript">
            var tid;
            function setTimeoutDemo() {
                tid = setTimeout("alert('下课了')", 3000);
            }
            function clearTimeoutDemo() {
                //判断tid是否初始化
                if (tid) {
                    clearTimeout(tid);
                }
            }
    
            var dir = "left"; 
            function scroll() {
                var title = window.document.title;
                if (dir == "left") {
                    var first = title.charAt(0);
                    var last = title.substring(1, title.length); //start 从0数  end从1数
                } else if (dir == "right") {
                    var last = title.charAt(title.length - 1);
                    var first = title.substring(0, title.length - 1);
                }
                window.document.title = last + first;
            }
            setInterval("scroll()", 500);
           
            function setDir(str) {
                dir = str;
            }
            
            
    
            function scrollRight() {
                var title = window.document.title;
                var last = title.charAt(title.length - 1);
                var first = title.substring(0, title.length - 1);
                title = last + first;
    
                window.document.title = title;
            }
    
            window.showModalDialog("1-.htm");
            
            function showDialog() {
                window.showModalDialog("1-.htm");
            }
            function show() {
                window.showModelessDialog("1-.htm");
            }
        </script>
    </head>
    <body>
        <input type="button" value="启动" onclick="setTimeoutDemo();" />
        <input type="button" value="取消" onclick="clearTimeoutDemo();" />
        
        
        <input type="button" value="向左" onclick="setDir('left')" />
        
        <input type="button" value="向右" onclick="setDir('right')" />
        <br />
        
        <input type="button" value="模式窗口" onclick="showDialog()" />
        <input type="button" value="非模式窗口" onclick="show()" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            var times = 10;
            function count() {
                var btn = document.getElementById("btn");
                if (times > 0) {
                    btn.value = "同意(倒计时" + times + ")";
                    times--;
                } else {
                    btn.value = "同意";
                    btn.disabled = false;
                    clearInterval(tid);
                }
            }
            var tid = setInterval("count()", 1000);
        </script>
    </head>
    <body onload="count()">
        注册协议
        <br />
        <input id="btn" type="button" value="同意" disabled="disabled" />
    </body>
    </html>
    

    window对象属性

    • window.location.href='http://www.itcast.cn',重新导向新的地址,和navigate方法效果一样。window.location.reload() 刷新页面
    • window.event是非常重要的属性,用来获得发生事件时的信息,事件不局限于window对象的事件,所有元素的事件都可以通过event属性取到相关信息。类似于winForm中的e(EventArg).
      • altKey属性,bool类型,表示发生事件时alt键是否被按下,类似的还有ctrlKey、shiftKey属性,例子 <input type="button" value="点击" onclick="if(event.altKey){alert('Alt点击')}else{alert('普通点击')}" /> ;
      • clientX、clientY 发生事件时鼠标在客户区的坐标;screenX、screenY 发生事件时鼠标在屏幕上的坐标;offsetX、offsetY 发生事件时鼠标相对于事件源(比如点击按钮时触发onclick)的坐标。
      • returnValue属性,如果将returnValue设置为false,就会取消默认事件的处理。在超链接的onclick里面禁止访问href的页面。在表单校验的时候禁止提交表单到服务器,防止错误数据提交给服务器、防止页面刷新。
      • srcElement,获得事件源对象。几个事件共享一个事件响应函数用。
      • keyCode,发生事件时的按键值。
      • button,发生事件时鼠标按键,1为左键,2为右键,3为左右键同时按。<body onmousedown="if(event.button==2){alert('禁止复制');}">

    (*)screen对象,屏幕的信息

    alert("分辨率:" + screen.width + "*" + screen.height);

    if (screen.width < 1024 || screen.height < 768){
    alert("分辨率太低!");
    }
    

    clipboardData对象

    • 对粘贴板的操作。clearData("Text")清空粘贴板;getData("Text")读取粘贴板的值,返回值为粘贴板中的内容;setData("Text",val),设置粘贴板中的值。
      • 案例:复制地址给友好。见备注。
      • 当复制的时候body的oncopy方法被触发,直接return false就是禁止复制。<body oncopy="alert('禁止复制!');return false;"
      • 很多元素也有oncopy、onpaste事件:
      • 案例:禁止粘贴帐号。见备注。
    • 在网站中复制文章的时候,为了防止那些拷贝党不添加文章来源,自动在复制的内容后添加版权声明。
    function modifyClipboard() {
    clipboardData.setData('Text', clipboardData.getData('Text') + '本文来自传智播客技术专区,转载请注明来源。' + location.href);
    }
    
    + `oncopy="setTimeout('modifyClipboard()',100)"`。用户复制动作发生0.1秒以后再去改粘贴板中的内容。100ms只是一个经常取值,写1000、10、50、200……都行。不能直接在oncopy里修改粘贴板。
    + 不能直接在oncopy中执行对粘贴板的操作,因此设定定时器,0.1秒以后执行,这样就不再oncopy的执行调用栈上了。
    
    • history操作历史记录
      • window.history.back()后退;window.history.forward()前进。也可以用window.history.go(-1)、window.history.go(1)前进
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function getXY() {
                document.title = window.event.clientX + "       " + window.event.clientY;
            }
            function turnInto(right) {
                if (right) {
                    alert("欢迎进入");
                } else {
                    alert("非法入侵");
                    window.event.returnValue = false;
                    alert("123123");
                }
            }
    
            function btnClick() {
                return false;
                alert("abc");
            }
    
            function txtKeyDown() {
                var txt = window.event.srcElement;
                if (txt.id == "txtNums") {
                    if (window.event.keyCode >= 48 && window.event.keyCode <= 57) {
                    } else {
                    return false;
                    }
                } else if (txt.id = "txt") { 
                    
                }
            }
        </script>
    </head>
    <body onmousemove="getXY()" onmousedown="if(window.event.button==2){alert('禁止复制')}">
        <input type="button" value="url" onclick="alert(window.location.href);" />
        <input type="button" value="转向" onclick="window.location.href='2-window对象.htm'" />
        <input type="button" value="reload" onclick="window.location.reload()" />
        <input type="button" value="ctrlKey" onclick="if(window.event.ctrlKey){alert('按下ctrl')}else{alert('没有按下')}" />
        <br />
        <a href="1-.htm" onclick="turnInto(0)">超链接</a>
        <input type="button" value="returnValue" onclick="btnClick();" />
        <form action="http://www.baidu.com">
            <input type="submit" onclick="alert('请输入用户名密码');window.event.returnValue=false"/>
        </form>
    
        <input id="txtNums" type="text" value="" onkeydown="return txtKeyDown()" />
        <input id="txt" type="text" value="" onkeydown="txtKeyDown()" />
        <input type="button" value="screen" onclick="alert(window.screen.width + ' ' + window.screen.height)" />
    
        <hr />
        手机号:<input type="text" value="" oncopy="alert('禁止复制');return false" /><br />
        
        重复手机号:<input type="text" value="" onpaste="alert('请输入');return false" />
        <hr />
        <input id="tabc" type="text" value="213123123" /><input type="button" value="copy" onclick="window.clipboardData.setData('text',tabc.value);alert('复制成功');" /><br />
        <input id="t123" type="text" value="" /><input type="button" value="paste" onclick="t123.value=clipboardData.getData('text')" /><br />
    
    </body>
    </html>
    
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function setClip() {
                var text = window.clipboardData.getData("text");
                text = text + "转载请注明:" + window.location.href;
                window.clipboardData.setData("text",text);
            }
        </script>
    </head>
    <body>
    
        <textarea id="t1" oncopy="setTimeout('setClip()',50)">
          asdfasdfasdf
            asdfasdfasdf
        
        </textarea>
        <a href="6-history.htm">链接</a>
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
    </head>
    <body>
        <input type="button" value="后退" onclick="window.history.back()" />
    </body>
    </html>
    
    

    document属性。

    是最复杂的属性之一。后面讲解详细使用。

    • document是window对象的一个属性,因为使用window对象成员的时候可以省略window.,所以一般直接写document

    • document的方法:

      • write:向文档中写入内容。writeln,和write差不多,只不过最后添加一个回车
    <input type="button" value="点击" onclick="document.write('<font color=red>你好</font>')" />
    
    + 在onclick等事件中写的代码会冲掉页面中的内容,只有在页面加载过程中write才会与原有内容融合在一起
    
    <script type="text/javascript">
    document.write('<font color=red>你好</font>');
    </script>
    
    + write经常在广告代码、整合资源代码中被使用。见备注
    

    内容联盟、广告代码、cnzz,不需要被主页面的站长去维护内容,只要被嵌入的js内容提供商修改内容,显示的内容就变了。

    • getElementById方法(非常常用),根据元素的Id获得对象,网页中id不能重复。也可以直接通过元素的id来引用元素,但是有有效范围、form1.textbox1之类的问题,因此不建议直接通过id操作元素,而是通过getElementById
    • (*)getElementsByName,根据元素的name获得对象,由于页面中元素的name可以重复,比如多个RadioButton的name一样,因此getElementsByName返回值是对象数组。
    • (*)getElementsByTagName,获得指定标签名称的元素数组,比如getElementsByTagName("p")可以获得所有的

      标签。

      • 案例:实现checkbox的全选,反选
      • 案例:点击一个按钮,被点击的按钮显示“呜呜”,其他按钮显示“哈哈”。
      • 案例:十秒钟后协议文本框下的注册按钮才能点击,时钟倒数。(btn.disabled = true )
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function writeDemo() {
                document.write("<a href='http://www.baidu.com'>百度</a>");
                document.write("<a href='http://www.baidu.com'>百度</a>");
                document.write("<a href='http://www.baidu.com'>百度</a>");
            }
            document.writeln("123<br/>");
            document.writeln("123<br/>");
            document.writeln("<a href='123.htm'>123</a>");
            document.write("<a href='http://www.baidu.com'>百度</a>");
            document.write("<a href='http://www.baidu.com'>百度</a>");
            document.write("<a href='http://www.baidu.com'>百度</a>");
            document.write("<ul><li>开始</li><li>运行</li><li>结束</li></ul>");
    
            //document.write("<script type='text/javascript'>alert('hello world');</script>");
        </script>
    </head>
    <body>
        <div>abc
        <script type="text/javascript">
            document.writeln("123<br/>");
            document.writeln("123<br/>");
           </script>abc
        </div>
        <div>
        sdfsd
        </div>
        <input type="button" value="按钮" onclick="writeDemo()" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function setText() {
                var txt = document.getElementById("t1");
                txt.value = "123";
                //t1.value = "123";
            }
            function setText2() {
                var txt = document.getElementById("t2");
                txt.value = "abc";
               //form1.t2.value = "abc";
            }
        </script>
    </head>
    <body>
        <input id="t1" type="text" value="" />
        <form id="form1">
            <input id="t2" type="text" value="" />
        </form>
        
        <input type="button" value="按钮" onclick="setText()" />
        <input type="button" value="按钮2" onclick="setText2()" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function btnClick() {
                var chks = document.getElementsByName("hobby");
                  //错误
    //            for (var c in chks) {
    //                alert(c);
                //            }
                for (var i = 0; i < chks.length; i++) {
                    //alert(chks[i].value);
                    chks[i].checked = "checked";
                }
            }
    
            function checkAll() {
                var chkAll = document.getElementById("chkAll");
                
                var chks = document.getElementsByName("hobby");
                for (var i = 0; i < chks.length; i++) {
                    chks[i].checked = chkAll.checked;
                }
            }
            function reverseCheck() {
                var chks = document.getElementsByName("hobby");
                for (var i = 0; i < chks.length; i++) {
                    chks[i].checked = !chks[i].checked;
                }
            }
            function checkSingle() {
                var b = true;    //假设全被选中   
                var chkAll = document.getElementById("chkAll");
                var chks = document.getElementsByName("hobby");
                for (var i = 0; i < chks.length; i++) {
                    //查找所有子的checkbox,判断是否被选中
                    //如果有一个checkbox没有被选中,则退出循环,最终全选的checkbox为false
                    if (!chks[i].checked) {
                        b = false;
                        break;
                    }
                }
                chkAll.checked = b;
            }
        </script>
    </head>
    <body>
        <input type="checkbox" value="cf" onclick="checkSingle()" name="hobby"/>吃饭<br />
        <input type="checkbox" value="sj" onclick="checkSingle()" name="hobby"/>睡觉<br />
        <input type="checkbox" value="ddd" onclick="checkSingle()" name="hobby"/>打豆豆<br />
        <br /><br />
        <input id="chkAll" type="checkbox" onclick="checkAll()"/>全选
        <input type="button" value="反选" onclick="reverseCheck()" />
        
        
        <input type="button" value="全选" onclick="btnClick()" />
       
        <br />
        <input type="checkbox" value="ctl" />春天里<br />
        <input type="checkbox" value="xtl" />夏天里<br />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function setAllText() {
                var txts = document.getElementsByTagName("input");
                for (var i = 0; i < txts.length; i++) {
                    if (txts[i].type == "text") {
                        txts[i].value = i + 1;
                    }
                }
            }
        </script>
    </head>
    <body>
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="button" value="按钮" onclick="setAllText()" />
    </body>
    </html>
    
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function init() {
                var btns = document.getElementsByTagName("input");
                for (var i = 0; i < btns.length; i++) {
                    if (btns[i].type == "button") { 
                        //给按钮注册单击事件(并没有调用)
                        btns[i].onclick = btnClick;
                    }
                }
            }
            
            function btnClick() {
                var btns = document.getElementsByTagName("input");
                for (var i = 0; i < btns.length; i++) {
                    if (btns[i].type == "button") {
                        //判断按钮 是不是事件源
                        if (btns[i] == window.event.srcElement) {
                            btns[i].value = "呜呜";
                        } else {
                            btns[i].value = "哈哈";
                        }
                    }
                }
            }
        </script>
    </head>
    <body onload="init()">
        <input type="button" value="哈哈" />
        <input type="button" value="哈哈"  />
        <input type="button" value="哈哈" />
        <input type="button" value="哈哈" />
        <input type="button" value="哈哈" />
        <input type="button" value="哈哈" />
        <input type="text" value="" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function add() {
                var txt1 = document.getElementById("txtNum1");
                var txt2 = document.getElementById("txtNum2");
                var num1 = parseInt(txt1.value);
                var num2 = parseInt(txt2.value);
                var sum = num1 + num2;
    
                document.getElementById("txtSum").value=sum;
            }
        
        </script>
    </head>
    <body>
        <input id="txtNum1" type="text" /><input type="button" value="+" />
        <input id="txtNum2" type="text" /><br />
        <input type="button" value="=" onclick="add()" /><br />
        <input id="txtSum" type="text" readonly="readonly" />
    </body>
    </html>
    

    dom动态创建

    document.write只能在页面加载过程中才能动态创建。
    可以调用document的createElement方法来创建具有指定标签的DOM对象,然后通过调用某个元素的appendChild方法将新创建元素添加到相应的元素下

    function showit() {
    var divMain = document.getElementById("divMain");
    var btn = document.createElement("input");
    btn.type = "button";
    btn.value = "我是动态的!";
    divMain.appendChild(btn);
    }
    <div id="divMain"></div>
    <input type="button" value="ok" onclick="showit()" />
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function createBtn() {
                var btn = document.createElement("input");
                btn.type = "button";
                btn.value = "新按钮";
                btn.onclick = function() {
                    alert("我是新来的");
                }
                var d = document.getElementById("d1");
                d.appendChild(btn);
            }
    
            function createLink() {
                var link = document.createElement("a");
                link.href = "http://www.baidu.com";
                link.innerText = "百度";
                link.target = "_blank";
    
                var d = document.getElementById("d1");
                d.appendChild(link);
            }
            
            function btnClick(){
                alert("我是新来的");
            }
        </script>
    </head>
    <body>
        <input type="button" value="创建按钮" onclick="createBtn()" />
        <input type="button" value="创建超链接" onclick="createLink()" />
        <div id="d1">abc</div>
    </body>
    </html>
    
    • Value 获取表单元素
    • 几乎所有DOM元素都有innerText、innerHTML属性(注意大小写),分别是元素标签内内容的文本表示形式和HTML源代码,这两个属性是可读可写的。
    <a href="http://www.itcast.cn" id="link1">传<font color="Red">智</font>播客</a>
    <input type="button" value="inner*" onclick="alert(document.getElementById('link1').innerText);alert(document.getElementById('link1').innerHTML);" />
    
    • 用innerHTML也可以替代createElement,属于简单、粗放型、后果自负的创建
    function createlink() {
    var divMain = document.getElementById("divMain");
    divMain.innerHTML = "<a href='http://www.rupeng.com'>如鹏网</a>";
    }
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function getLinkText() {
                var link = document.getElementById("link1");
                alert(link.innerText);
                alert(link.innerHTML);
            }
            function setDiv() {
                var div = document.getElementById("d1");
                //div.innerText = "<font color='red'>123123</font>";
                //div.innerHTML = "<font color='red'>123123</font>";
                //div.innerHTML = "<ul><li>春天里</li><li>怒放</li></ul>";
                //div.innerHTML = "<input type='text' value='1234' />";
    
                //div.innerText = div.innerText + "123123";
    
                //Node节点 Element元素的区别
                //html文档里所有的内容都是节点 标签 属性  文本
                //元素  一个完整的标签
    			//var txtNode = document.createTextNode("123123");
                //            div.appendChild(txtNode);
    
                div.innerHTML = "<script type='text/javascript'>function test(){alert('hello');}</script>";
            }
        </script>
    </head>
    <body>
        <a id="link1" href="http://www.itcast.cn">传智<font color="red">播客</font></a>
        
        
        <input type="button" value="按钮" onclick="getLinkText()" />
        <div id="d1">abcd</div>
        
        <input type="button" value="set div" onclick="setDiv() " />
        
            <input type="button" value="test" onclick="test()" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function createTable() {
                var div = document.getElementById("d1");
                var dic = { "baidu": "http://www.baidu.com", "传智播客": "http://www.itcast.cn", "cnbeta": "http://www.cnbeta.com" };
                var table = document.createElement("table");
                table.border = 1;
                for (var key in dic) {
                    var tr = document.createElement("tr");
                    var td0 = document.createElement("td");
                    td0.innerText = key;
                    //把td0加到tr中
                    tr.appendChild(td0);
    
                    var td1 = document.createElement("td");
                    td1.innerHTML = "<a href='" + dic[key] + "'>" + dic[key] + "</a>";
                    tr.appendChild(td1);
                    //把tr添加到table中
                    table.appendChild(tr);
                }
                //把table添加到div中
                div.appendChild(table);
            }
        
        </script>
    </head>
    <body>
        <div id="d1"></div>
        <input type="button" value="load。。。" onclick="createTable()" />
    </body>
    </html>
    

    浏览器兼容性的例子

    ie6,ie7对table.appendChild("tr")的支持和IE8不一样,用insertRow、insertCell来代替或者为表格添加tbody,然后向tbody中添加tr。FF不支持InnerText。

    所以动态加载网站列表的程序修改为:

    var tr = tableLinks.insertRow(-1);//FF必须加-1这个参数
    var td1 = tr.insertCell(-1);
    td1.innerText = key;
    var td2 = tr.insertCell(-1);
    td2.innerHTML = "<a href='" + value + "'>" + value + "</a>";
    

    或者:

    <table id="tableLinks">
    <tbody></tbody>
    </table>,然后tableLinks. tBodies[0].appendChild(tr);
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        
        <script type="text/javascript">
            function add() {
                var name = document.getElementById("txtName").value;
                var content = document.getElementById("txtContent").value;
    
                var tr = document.createElement("tr");
                var td0 = document.createElement("td");
                td0.innerText = name;
                tr.appendChild(td0);
    
                var td1 = document.createElement("td");
                td1.innerText = content;
                tr.appendChild(td1);
    
                var table = document.getElementById("re");
                table.appendChild(tr);
            }
        </script>
    </head>
    <body>
        <p>
            最新新闻
        </p>
        
        <table id="re"></table>
        <hr />
        
        评论:
            <input id="txtName" type="text" value="" /><br />
            <textarea id="txtContent" cols="50" rows="10"></textarea>
            
            <br />
            
            <input type="button" value="评论" onclick="add()" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function add() {
                var name = document.getElementById("txtName").value;
                var content = document.getElementById("txtContent").value;
                
                var table = document.getElementById("re");
                var tr = table.insertRow(-1);
                
                var td = tr.insertCell(-1);
                td.innerHTML = name;
    
                var td1 = tr.insertCell(-1);
                td1.innerHTML = content;
                
            }
        
        </script>
    </head>
    <body>
        <p>
            最新新闻
        </p>
        
        <table id="re"></table>
        <hr />
        
        评论:
            <input id="txtName" type="text" value="" /><br />
            <textarea id="txtContent" cols="50" rows="10"></textarea>
            
            <br />
            
            <input type="button" value="评论" onclick="add()" />
    </body>
    </html>
    

    事件冒泡

    事件冒泡:如果元素A嵌套在元素B中,那么A被点击不仅A的onclick事件会被触发,B的onclick也会被触发。触发的顺序是“由内而外” 。验证:在页面上添加一个table、table里有tr、tr里有td,td里放一个p,在p、td、tr、table中添加onclick事件响应,见备注。

    <table onclick="alert('table onclick');">
    <tr onclick="alert('tr onclick');">
    <td onclick="alert('td onclick');"><p onclick="alert('p onclick');">aaaa</p></td>
    <td>bbb</td>
    </tr>
    </table>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function btn3() {
                alert(event.srcElement.value);
            }
            //事件响应函数的调用函数
            function btn4() {
                alert(this.value);
            }
    
            function initBtn5() {
                var btn = document.getElementById("btn5");
                //事件响应函数
                btn.onclick = btn4;
            }   
        </script>
    </head>
    <body onload="initBtn5()">
       <table onclick="alert('table')">
        <tr onclick="alert('tr')">
            <td onclick="alert('td')"> <div onclick="alert('div')">asd</div></td>
            <td>2</td>
        </tr>
       </table>
       
       <input type="button" value="click1" onclick="alert(event.srcElement.value)" /><br />
       <!-- 事件响应函数-->
       <input type="button" value="click2" onclick="alert(this.value)" />
       
       <input type="button" value="click3" onclick="btn3()" />
       <input type="button" value="click4" onclick="btn4()" />
       
       <input id="btn5" type="button" value="click5" />
       
       
    </body>
    </html>
    
    

    this

    事件中的this。

    除了可以使用event.srcElement在事件响应函数中

    this表示发生事件的控件。

    只有在事件响应函数才能使用this获得发生事件的控件,在事件响应函数调用的函数中不能使用,如果要使用则要将this传递给函数或者使用event.srcElement。

    (*)this和event.srcElement的语义是不一样的,this就是表示当前监听事件的这个对象,event.srcElement是引发事件的对象:事件冒泡。

    修改样式

    易错:修改元素的样式不是设置class属性,而是className属性。案例:网页开关灯的效果。
    修改元素的样式不能this.style="background-color:Red"
    易错:单独修改样式的属性使用“style.属性名”。注意在css中属性名在JavaScript中操作的时候属性名可能不一样,主要集中在那些属性名中含有-的属性,因为JavaScript中-是不能做属性、类名的。所以CSS中背景颜色是background-color,而JavaScript则是style.backgroundColor;元素样式名是class,在JavaScript中是className属性;font-size→style.fontSize;margin-top→style.marginTop
    单独修改控件的样式<input type="button" value="AAA" onclick="this.style.color='red'" />。技巧,没有文档的情况下的值属性名,随便给一个元素设定id,然后在js中就能id.style.出来能用的属性。

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <style type="text/css">
            .light{
                background-color:White;
            }
            .dark
            {
            	background-color:Black;
            }
        </style>
        <script type="text/javascript">
            function open1() {
                document.body.className = "light";
            }
            function close1() {
                document.body.className = "dark";
            }
    
            function change() {
                var txt = document.getElementById("txt1");
                //错误 不能这样用。可以把style看成一个只读属性
                //txt.style = "background-color:Green";
                
                txt.style.backgroundColor = "Green";
                txt.style.color = "red";
            }
        </script>
    </head>
    <body>
    <input type="button" value="开灯" onclick="open1()" />
    <input type="button" value="关灯" onclick="close1()" />
    
    <input id="txt1" type="text" value="123" />
    <input type="button" value="click" onclick=" change() " />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function initTxt() {
                var txts = document.getElementsByTagName("input");
                for (var i = 0; i < txts.length; i++) {
                    if (txts[i].type == "text") {
                        //事件响应函数
                        txts[i].onblur = iBlur;
                    }
                }
            }
        
            function iBlur() {
                if (this.value.length <= 0) {
                    this.style.backgroundColor = "red";
                } else {
                this.style.backgroundColor = "white";
                }
            }
            function iFocus(txt) {
                txt.value = "";
            }
        </script>
    </head>
    <body onload="initTxt()">
        <input type="text" value=""/>
        <input type="text" value="" />
        <input type="text" value="" />
        
        <input type="button" value="click" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function iBlur(txt) {
                var t2 = document.getElementById("t2");
                t2.style.backgroundColor = txt.style.backgroundColor;
                t2.style.color = txt.style.color;
                t2.style.width = txt.style.width;
                t2.value = txt.value;
            }
            function iFocus(txt) {
                var t1 = document.getElementById("t1");
                txt.style.backgroundColor = t1.style.backgroundColor;
                txt.style.color = t1.style.color;
                txt.style.width = t1.style.width;
                txt.value = t1.value;
            }
        </script>
    </head>
    <body>
        <input id="t1" type="text" value="" style="background-color:Green; color:Red; 300px" />
        <input type="text" onfocus="iFocus(this)" />
    </body>
    </html>
    
    <head>
        <title></title>
        <script type="text/javascript">
            
            
            function init() {
                var table = document.getElementById("rating");
                var tds = table.getElementsByTagName("td");
                for (var i = 0; i < tds.length; i++) {
                    //事件响应函数
                    tds[i].onmouseover = change;
                    tds[i].onclick = stop;
                    tds[i].style.cursor = "pointer";
                }
            }
            //记录是否点鼠标,默认没点
            var isClick = false;
            function stop() {
                isClick = true;
            }
            function indexOf(arr,element){
                var j = -1;
                for(var i=0;i<arr.length;i++){
                    if(arr[i] == element)
                    {
                        j = i;
                        break;
                    }
                }
                return j;
            }
            function change() {
                //当没点鼠标的时候去执行
                if (!isClick) {
                    var table = document.getElementById("rating");
                    var tds = table.getElementsByTagName("td");
                    var n = indexOf(tds, this);
                    for (var i = 0; i <= n; i++) {
                        //tds[i].style.backgroundColor = "red";
                        tds[i].innerText = "★";
                    }
    
                    for (var i = n + 1; i < tds.length; i++) {
                        //tds[i].style.backgroundColor = "white";
                        tds[i].innerText = "☆";
                    }
                }
                
            }
        </script>
    </head>
    <body onload="init()">
        <table id="rating">
            <tr>
                <td>☆</td><td>☆</td><td>☆</td><td>☆</td><td>☆</td>
            </tr>
        </table>
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function init() {
                var d1 = document.getElementById("d1");
                var links = d1.getElementsByTagName("a");
                for (var i = 0; i < links.length; i++) {
                    links[i].onclick = linkClick;
                }
            }
            function linkClick() {
                var d1 = document.getElementById("d1");
                var links = d1.getElementsByTagName("a");
                //当前a标签变成红色
                this.style.backgroundColor = "red";
                //让其它标签变成白色
                for (var i = 0; i < links.length; i++) {
                    if (links[i] != this) {
                        links[i].style.backgroundColor = "white";
                    }
                }
    
                //取消后续内容的执行
                    window.event.returnValue = false;
            }
        </script>
    </head>
    <body onload="init()">
        <div id="d1">
            <a href="http://www.baidu.com">百度</a>
            <a href="http://www.qiushibaike.com">糗百</a>
            <a href="http://www.cnbeta.com">cnbeta</a>
        </div>
        <div id="d2">
            <a href="http://www.baidu.com">百度</a>
            <a href="http://www.qiushibaike.com">糗百</a>
            <a href="http://www.cnbeta.com">cnbeta</a>
        </div>
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function init() {
                var table = document.getElementById("students");
                var trs = table.getElementsByTagName("tr");
                for (var i = 0; i < trs.length; i++) {
                    //鼠标经过的时候,换颜色
                    trs[i].onmouseover = onOver;
                    //当鼠标离开时候,还原颜色
                    trs[i].onmouseout = onOut;
                    //隔行换色
                    if (i % 2 == 0) {
                        trs[i].style.backgroundColor = "red";
                    } else {
                    trs[i].style.backgroundColor = "yellow";
                    }
                }
            }
            var defaultColor;
            function onOver() {
                defaultColor = this.style.backgroundColor;
                this.style.backgroundColor = "gray";
            }
            function onOut() {
                this.style.backgroundColor = defaultColor;
            }
        </script>
    </head>
    <body onload="init()">
        <table id="students" border="1" width="400px">
            <tr>
                <td>刘备</td>
                <td>男</td>
                <td>19</td>
            </tr>
            <tr>
                <td>关羽</td>
                <td>男</td>
                <td>18</td>
            </tr>
            <tr>
                <td>张飞</td>
                <td>男</td>
                <td>17</td>
            </tr>
            <tr>
                <td>曹操</td>
                <td>男</td>
                <td>20</td>
            </tr>
            <tr>
                <td>吕布</td>
                <td>男</td>
                <td>19</td>
            </tr>
        </table>
    </body>
    </html>
    
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <script type="text/javascript">
            function init() {
                var txts = document.getElementsByTagName("input");
                for (var i = 0; i < txts.length; i++) {
                    if (txts[i].type == "text") {
                        txts[i].onfocus = function() { this.style.backgroundColor = "red"; };
                        txts[i].onblur = function() { this.style.backgroundColor = "white"; };
                    }
                }
            }
            function reset() {
                this.style.backgroundColor = "white";
            }
            function change() {
                this.style.backgroundColor = "red";
    //            
    //            var txts = document.getElementsByTagName("input");
    //            for (var i = 0; i < txts.length; i++) {
    //                if (txts[i] != this) {
    //                    txts[i].style.backgroundColor = "white";
    //                }
    //            }
                
            }
        </script>
    </head>
    <body onload="init()">
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        <input type="text" value="" />
        
        <input type="button" value="按钮" />
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
        <style type="text/css">
            #l li
            {
            	300px;
            	list-style-type:none;
            	float:left;
            	}
        </style>
       <script type="text/javascript">
           function init() {
           
               var ul = document.getElementById("l");
               var lis = ul.getElementsByTagName("li");
               for (var i = 0; i < lis.length; i++) {
                   lis[i].style.cursor = "pointer";
                   
                   lis[i].onclick = function() {
                       var ul = document.getElementById("l");
                       var lis = ul.getElementsByTagName("li");
                       this.style.backgroundColor = "red";
                       for (var i = 0; i < lis.length; i++) {
                           if (lis[i] != this) {
                               lis[i].style.backgroundColor = "white";
                           }
                       }
                   };
               }
           }
       </script>
    </head>
    <body onload="init()">
        <ul id="l">
            <li>C#</li>
            <li>java</li>
            <li>JavaScript</li>
            <li>html</li>
        </ul>
    </body>
    </html>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title></title>
       
        <script type="text/javascript">
            function hide(btn) {
                var div = document.getElementById("d1");
                if (div.style.display == "none") {
                    div.style.display = "";
                    btn.value = "隐藏";
                }else{
                div.style.display = "none";
                btn.value = "显示";
                }
            }
            function show() {
                var div = document.getElementById("d1");
                div.style.display = "";
            }
    
            function detailsShow(chk) {
                var div = document.getElementById("d3");
                if (chk.checked) {
                    div.style.display = "";
                } else {
                    div.style.display = "none";
                }
            }
    
            function aOver() {
                //screenX 鼠标在屏幕中坐标
                var div = document.getElementById("d4");
                div.style.position = "absolute";
                div.style.top = window.event.clientY;//鼠标在浏览器中的位置
                div.style.left = window.event.clientX;
                div.style.display = "";
    
            }
            function aOut() {
                var div = document.getElementById("d4");
                div.style.display = "none";
            }
        </script>
    </head>
    <body>
        <div id="d1">
            怎么会迷上你,我在问自己。。。
        </div>
        <div id="d2">
            春天里百花香
        </div>
        <input type="button" value="隐藏" onclick="hide(this)" />
        <input type="button" value="显示" onclick="show()" />
        <hr />
        
        <input type="checkbox" onclick="detailsShow(this)" />显示详细信息
        <div id="d3" style=" display:none">
            详细信息
        </div>
        
        <hr />
        
        <a href="http://www.baidu.com" onmouseover="aOver()" onmouseout="aOut()">百度</a>
        <a href="http://www.google.com" onmouseover="aOver()"  onmouseout="aOut()">google</a>
        <a href="http://www.sougou.com" onmouseover="aOver()"  onmouseout="aOut()">sougou</a>
        
        <div id="d4" style=" display:none; border:dotted 1px red;">
            <img src="IMG_8910.jpg" width="200px" height="100px" />
            <br />我拍的照片
            <br />赵苑
        </div>
    </body>
    </html>
    
  • 相关阅读:
    解决SQL Server Compact 无法在64位系统下正常运行
    Mvc5+Entity Framework6 之二----在MVC中用Entity Framework实现基本的CRUD
    Asp.net MVC5中Html.DropDownList的使用
    C# 使用微软的Visual Studio International Pack 类库提取汉字拼音首字母
    MVC学习 (二) Razor语法
    MVC学习 (一)
    编程实现机器人相遇
    jquery优化引发的思考
    (续)检测到有潜在危险的 Request.Form 值
    检测到有潜在危险的 Request.Form 值
  • 原文地址:https://www.cnblogs.com/lovexinyi/p/10655930.html
Copyright © 2011-2022 走看看