文本框获得失去焦点——js和jquery方法的对比

来源:互联网 发布:tcga数据下载 编辑:程序博客网 时间:2024/06/06 00:48
 

Js方法

<head>
    <script type="text/javascript">
        function Doit() {

            // 获得一个input的数组,需要遍历
            var inputs = document.getElementsByTagName_r("input");            

              for (var i = 0; i < inputs.length; i++) {
               
               // 如果是文本控件
                if (inputs[i].type == "text") {

                    // 前面有on——
                    inputs[i].onfocus = function () {

                        // 通过this直接获取触发的元素
                       this.style.backgroundColor = "yellow";
                    };
                    inputs[i].onblur = function () {
                        this.style.backgroundColor = "white";
                    };
                }
              
            }
        }
    </script>
</head>
<body onload="Doit()">
    <input id="Text1" type="text" />
    <input id="Text2" type="text" />
    <input id="Text3" type="text" />
    <input id="Button1" type="button" value="button" />
</body>
</html>

 

Jquery方法

<head>
    <script src="jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {

            // 不需要遍历
            $('input[type=text]').click(function () {

               // this前面要加dollar符
               $(this).css("backgroundColor","yellow");
            }).blur(function () { $(this).css("backgroundColor","white");});

            // blur前面没有on
        });
    </script>
</head>
<body>
    <input id="Text1" type="text" />
    <input id="Text2" type="text" />
    <input id="Text3" type="text" />
    <input id="Button1" type="button" value="button" />
</body>
</html>

原创粉丝点击