<label for="name">请输入您的名字</label>
<input type="text" id="username"/>
怎样使用jquery代码,使input输入框在失去焦点时,使用label的属性值

解决方案 »

  1.   

    label????
    原生的加个onblur事件不就行了么- -。。
      

  2.   

    给text价格onblur事件试试 
    不明白你  使用label的属性值的意思
      

  3.   

    你要的, 是这个效果吧?
    <html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
        <style type="text/css">
            .gray{ color:Gray; }
        </style>
        <script type="text/javascript">
            $(function(){
                //定义缓存变量
                var $username = $("#username");
                //初始就设置为 label 中的文字
                $username.addClass("gray").val($("label[for='"+$username.attr("id")+"']").html());
                //失焦点时,如果没有文字则 设置为 label 中的文字
                $username.blur(function(){
                    if($.trim(this.value)==""){
                        $(this).addClass("gray").val($("label[for='"+this.id+"']").html());
                    }
                })
                //得焦点时,如果原来是灰色样式,则移除灰色样式,并清空。
                .focus(function(){
                    if($(this).hasClass("gray")){
                        $(this).removeClass("gray").val("");
                    }
                });
            });
        </script>
    </head>
    <body>
    <div>
        <label for="username">请输入您的名字</label>:<input type="text" id="username" />
    </div>
    </body>
    </html>