<!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/ecmascript">
    function ObjectA()
    {
        this.BuildControl = function()
        {
            var new_bar = document.createElement("div");
            for (var cot = 0;cot < 3;cot++)
            {
                var new_btn = document.createElement("input");
                new_btn.type = "button";
                new_btn.value = cot.toString();
                new_btn.onclick = function()
                {
                    alert(cot.toString());
                }
                new_bar.appendChild(new_btn);
            }
            document.getElementById("test").appendChild(new_bar);
        }
    }
    </script>
</head>
<body onload="var new_a = new ObjectA();new_a.BuildControl();">
<div id="test"></div>
</body>
</html>
这段代码照例说应该产生三个按钮,点击后依次是现实对话框1/2/3
但是事实运行的结果是3个按钮全部都是显示3,想了半天不知为啥,不知哪位高手能解决一下

解决方案 »

  1.   

    其实不是什么帮定事件的问题 是楼主的问题 因为在你点击按钮的时候 3个按钮都已经生成
    也就是for循环已经完毕,当你点击按钮的时候cot就已经等于3了"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html   xmlns="http://www.w3.org/1999/xhtml"   > <head> 
            <title> </title> 
            <script   type="text/ecmascript"> 
            function   ObjectA() 
            { 
                    this.BuildControl   =   function() 
                    { 
                            var   new_bar   =   document.createElement("div"); 
                            for   (var   cot   =   0;cot   <   3;cot++) 
                            { 
                                    var   new_btn   =   document.createElement("input"); 
                                    new_btn.type   =   "button"; 
                                    new_btn.value   =   cot.toString(); 

                                    new_btn.onclick   =   function() 
                                    { 

                                            alert(this.value); 
                                    } 
                                    new_bar.appendChild(new_btn); 
                            } 
                            document.getElementById("test").appendChild(new_bar); 
                    } 
            } 
            </script> 
    </head> 
    <body   onload="var  new_a = new   ObjectA();new_a.BuildControl();"> 
    <div   id="test"> </div> 
    </body> 
    </html>