日期:2014-05-16  浏览次数:20364 次

超简单的问题..动态添加事件
进行动态添加的时候,进循环..获得焦点和失去焦点的方法都能加进去.

 但是attachEvent里面function里的nInput总是对应nDiv.getElementsByTagName("input")[5];
JScript code
<script type="text/javascript">
        var oldv;

        function test() {
            var nDiv = document.getElementById("div1");
            if (window.attachEvent) {
                var nInput;
                for (var i = 0; i < nDiv.getElementsByTagName("input").length; i++) {
                    nInput = nDiv.getElementsByTagName("input")[i];
                    
                    nInput.attachEvent("onfocus", function () {
                           oldv = nInput.value; 
                           nInput.style.color = "Black"; 
                           nInput.value = ""; });
                
                    nInput.attachEvent("onblur", function () {
                        if (nInput.value == "") {
                            nInput.value = oldv;
                            nInput.style.color = "Gray";
                        }
                    });
                }
            }
            else {
                alert("2");
            }

        }
       
    </script>


C# code

    <form runat="server" id="form1">
    <div id="div1">
        <table>
            <tr>
                <td align="right">用户名:</td>
                <td><input id="Text1" type="text"  value="USER NAME" style="color:Gray"  /></td>
            </tr>
            <tr>
                <td align="right">昵称:</td>
                <td><input id="Text2" type="text"  value="NIC NAME"  style="color:Gray"  /></td>
            </tr>
            <tr>
                <td align="right">密码:</td>
                <td><input id="Text3" type="text"  value="PASSWORD" style="color:Gray"  /></td>
            </tr>
            <tr>
                <td align="right">确认密码:</td>
                <td><input id="Text4" type="text"  value="CONFIRM PASSWORD"  style="color:Gray"  /></td>
            </tr>
            <tr>
                <td align="right">邮箱:</td>
                <td><input id="Text5" type="text"  value="EMAIL" style="color:Gray"  /></td>
            </tr>
            <tr>
                <td align="right">电话:</td>
                <td><input id="Text6" type="text"  value="TELEPHONE"  style="color:Gray"  /></td>
            </tr>
            </table>
    </div>
        <table>
             <tr>
                <td><input id="Button1" type="button" value="提交" /></td>
                <td colspan = "30"></td>
                <td><input id="Button2" type="button" value="返回" /></td>
            </tr>
        </table>
   </form>



------解决方案--------------------
JScript code
// 通用代码
<script type="text/javascript">
var oldv = "";
    
function onfo