jQuery操作input改變value屬性值


今天寫了一個表單元素,在用戶點擊的時候會清空input中的內容,當鼠標點擊其他地方的時候會把輸入的值保存為input的value值

類似於這樣的效果

當用戶點擊的時候文字消失。

html代碼

     <input type="text" name="" value="請輸入您的郵箱地址"/>
     <input type="text" name="" value="請輸入用戶名"/>
     <input class="pwd" type="text" name="" value="請輸入密碼"/>
     <input class="pwd" type="text" name="" value="確認密碼"/>
jq代碼
<script type="text/javascript">
	$(document).ready(function(e) {
        var temp;
        $(":text").focusin(function(){
            var value = $(this).val();
            if ($(this).val() == "請輸入密碼" || $(this).val() == "請輸入您的郵箱地址" || $(this).val() == "確認密碼" || $(this).val() =="請輸入用戶名") {				
				if($(this).val() == "確認密碼" || $(this).val() == "請輸入密碼") {
					$(this).attr('type','password')
				}
                $(this).val("")
			}
            //alert(value)
		})
		$(":input").focusout(function(event) {
            /* Act on the event */
            if($(this).val() == "") {              
                if ($(this).hasClass('pwd')) {
                    $(this).attr('type','text')
                };
                $(this).val(temp)
            }
        });
    })

</script>

這樣之后基本所要求的功能可以實現,但是發現代碼不夠優雅,於是又想到了可以使用數組來保存value值,

var arr_ = [];
        var temp;
        $(":text").each(function() {
            arr_.push($(this).val())
        })
        $(":text").focusin(function(){
			var that = this;
            var value = $(that).val();
            temp = value;
            $.each(arr_,function(i,n) {
				if(value==n){
					$(that).val("");
					if(value=="請輸入密碼"||value=="確認密碼"){
						$(that).attr("type","password");
					}
				}
            });
		})

又發現了一個問題, 總是需要一個全局變量temp來保存value值,這對於javascript來說是不好的,於是乎又想到了data屬性

<input type="text" name="" data="請輸入您的郵箱地址" value="請輸入您的郵箱地址"/>
            <input type="text" name="" data="請輸入用戶名" value="請輸入用戶名"/>
            <input class="pwd" type="text" data="請輸入密碼" name="" value="請輸入密碼"/>
            <input class="pwd" type="text" data="確認密碼" name="" value="確認密碼"/>

$(document).ready(function(e) {
        var arr_ = [];
        $(":text").each(function() {
            arr_.push($(this).val())
        })
        $(":text").focusin(function(){
			var that = this;
            var value = $(that).val();
            $.each(arr_,function(i,n) {
				if(value==n){
					$(that).val("");
					if(value=="請輸入密碼"||value=="確認密碼"){
						$(that).attr("type","password");
					}
				}
            });
		})
		$(":input").focusout(function(event) {
            /* Act on the event */
            if($(this).val() == "") {              
                if ($(this).hasClass('pwd')) {
                    $(this).attr('type','text')
                };
                $(this).val($(this).attr("data"));
            }
        });
    })

這樣便看起來舒服多了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM