zoukankan      html  css  js  c++  java
  • javascript作用域问题

    为某个节点下注册事件常犯错误纠正:

    View Code
    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>


    <style type="text/css">
    ul li{100px; height:20px; background: #CCC; border: solid 1px black;};
    </style>
    <script language="javascript" >
    /*
    IE和firfox childNodes属性的区别
    也把一个标签的结束符“>”到下一个标签的起始符“<”之间的内容
    (除注释外,包括任何的文字、空格、回车、制表符)也算是一个节点了。
    而且这种节点也有它们自己独特的属性和值--nodeName="#text"。
    */
    window.onload=function(){
    var nodes=document.getElementById("a").childNodes;
    alert(nodes.length);
    for(var i=0;i<nodes.length;i++){
    /*
    调用这个nu这个方法,变量的值只在这个函数的作用域里面
    */
    nu(nodes[i],i+1);
    /*
    如果像如下这么做的话那么每点击一个几点的时候返回的值是nodes.length,而不是我们期望的值。
    这里存在一个作用域的问题;因为当点击某个节点的时候才会执行相应的方法,但是此方法是得到循环完过后的值的。
    也就是说这里的i的值并没有被销毁
    nodes[i].onclick=function(){
    alert(i);
    }
    */
    }
    }

    function nu(node,i){
    node.onclick=function(){
    alert(i);
    }
    }

    </script>

    </head>

    <body>

    <ul id="a">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    </ul>
    </body>
    </html>



  • 相关阅读:
    POJ 2195 Going Home(费用流)
    HDU 2485 Destroying the bus stations(费用流)
    POJ 3281 Dining(最大流)
    POJ 1122 FDNY to the Rescue!(最短路+路径输出)
    HDU 4747 Mex(线段树)
    POJ 2337 Catenyms
    UVa 10328 Coin Toss(Java大数+递推)
    HDU 1811 Rank of Tetris(拓扑排序+并查集)
    ZOJ 3747 Attack on Titans
    UVa 11404 回文子序列(LCS求最长回文串长度)
  • 原文地址:https://www.cnblogs.com/unbreakable/p/2437258.html
Copyright © 2011-2022 走看看