如果输入框为空,Jquery在失去焦点时返回原始值

4
我应该如何实现这个功能?如果用户留空了字段,我想要获得原始值。
这是我目前的代码:Jsfiddle Demo
$(document).ready(function() {
    var field = $('input[type="text"]');
    field.focus(function() { //Empty the field on focus
        var thisValue = $(this).val();
        $(this).attr("value", "");
    });

    field.blur(function() { //Check the field if it is left empty
        if ($(this).val() == "") {
            //alert('This field can not be left empty');
            $(this).val(thisValue);
        }
    });
});​
6个回答

5
您基本上在描述placeholder属性,这个属性在所有主流浏览器中都有原生支持。但是,在旧版浏览器中不支持该属性。为了获得更广泛的支持,您需要为此属性添加shim支持。在线上有很多选项可以帮助您完成这个过程,但如果您愿意,也可以自己完成。基本上,您希望允许自己和其他人使用标准标记:
<input name="fname" placeholder="First Name">

使用jQuery,您可以响应具有placeholder属性的任何元素的focusblur(或focusinfocusout)事件。如果一个元素被聚焦,并且具有占位符值,则清除该元素。如果元素失去焦点并为空,则提供占位符值。
这有点冗长,但我已经添加了注释以帮助理解逻辑:
// Written and tested with jQuery 1.8.1
(function ( $ ) {

    // Play nice with jshint.com
    "use strict";

    // Abort if browser already supports placeholder
    if ( "placeholder" in document.createElement("input") ) {
        return;
    }

    // Listen at the document level to work with late-arriving elements
    $(document)
        // Whenever blur or focus arrises from an element with a placeholder attr
        .on("blur focus", "[placeholder]", function ( event ) {
            // Determine the new value of that element
            $(this).val(function ( i, sVal ) {
                // First store a reference to it's placeholder value
                var placeholder = $(this).attr("placeholder"), newVal = sVal;
                // If the user is focusing, and the placehoder is already set
                if ( event.type === "focusin" && sVal === placeholder ) {
                    // Empty the field
                    newVal = "";
                }
                // If the user is blurring, and the value is nothing but white space
                if ( event.type === "focusout" && !sVal.replace(/\s+/g, "") ) {
                    // Set the placeholder
                    newVal = placeholder;
                }
                // Return our new value
                return newVal;
            });
        })
        // Finally, when the document has loaded and is ready
        .ready(function () {
            // Find non-autofocus placeholder elements and blur them
            // This triggers the above logic, which may provide default values
            $(":input[placeholder]:not([autofocus])").blur();
        });

}(jQuery));

这个 shim 只提供基本功能。其他的可能会扩展支持,当占位符值被使用时更改字体颜色,以及在开始输入之前保留占位符值可见(这种方法只是在焦点上立即删除它)。

不错,但是你要冒着文本框的值在脚本将默认值复制到“数据”缓存之前发生更改的风险。 - gdoron
不要误会,我非常喜欢你的回答!但是“风险”应该被注意到,所以我做了注释... :) - gdoron
请注意,如文档中所述,:text 选择器的性能较差:“因为 :text 是 jQuery 的扩展,而不是 CSS 规范的一部分,使用 :text 进行查询无法利用本机 DOM querySelectorAll() 方法提供的性能提升。为了获得更好的现代浏览器性能,请改用 [type="text"]。” - gdoron
@gdoron 感谢您的留言。这只是表明,简短并不总是更好的选择 ;) - Sampson
.focusout.blur 之间有区别。 - eric.dummy
显示剩余3条评论

1

这里还有一个非jQuery的答案:

<input type="text" name="zip_code" id="zip_code_value" value="Name" onfocus="if(this.value=='Name'){this.value=''}" onblur="if(this.value==''){this.value='Name'}">

您可以将输入标签更新为这样,然后就不需要使用jQuery了。


1

占位符:

$(document).ready(function() {
    var field = $('input[type="text"]');
    field.focus(function() {
        var placeholder = $(this).data('placeholder');
        if (this.value == placeholder) 
            this.value = "";

    });

    field.blur(function() {
        if (this.value === "") {
            this.value = $(this).data('placeholder');
        }
    });
});​

实时演示

关于$(this).val()

了解您的DOM属性和函数

虽然jQuery的目标之一是抽象出DOM,但了解DOM属性可能非常有用。那些在学习jQuery而不了解DOM的人最常犯的错误之一是利用jQuery强大的功能来访问元素的属性:

$('img').click(function() {
    $(this).attr('src');  // Bad! 
}); 

在上述代码中,this 指的是触发 click 事件处理程序的元素。上面的代码既慢又啰嗦;下面的代码功能相同,但更短、更快和更易读。 jQuery 标签信息

0

你应该将thisValue设置为全局变量,这样它就可以在所有地方被访问到。像这样:

$(document).ready(function() {
    var field = $('input[type="text"]');
    var thisValue
    field.focus(function() {//Empty the field on focus
        thisValue = $(this).val();
        $(this).attr("value","");
    });

    field.blur(function() {//Check the field if it is left empty
        if($(this).val()=="") {
        //alert('This field can not be left empty');
        $(this).val(thisValue);
        }
    });

0

这是我最近一直在使用的:

HTML:

<input type="text" name="s" id="s" value="Search" />
<input type="text" name="email" id="email" value="you@domain.com" />
...

JavaScript:

// Default Input Field Text
$(document).ready( function(){
    $("#s, #email, #phone, #name").live("focus", function(){
        if ( $(this).val() == $(this).attr("rel") ) $(this).val('');
    }).live("blur", function(){
        if ( $(this).val() == '' ) $(this).val( $(this).attr("rel") );
    }).each( function(){
        $(this).attr("rel", $(this).val() );
    });
});

0

通过删除 var,在全局范围内定义 thisValue

$(document).ready(function() {
    var field = $('input[type="text"]');
    field.focus(function() {//Empty the field on focus
         thisValue = $(this).val();
        $(this).attr("value","");
    });

    field.blur(function() {//Check the field if it is left empty
        if($(this).val()=="") {
        //alert('This field can not be left empty');
        $(this).val(thisValue);
        }
    });
});

http://jsfiddle.net/dbsNy/3/


我没有给你点踩,但我不确定这是否是原帖作者真正想要的。你只是提供了一个警告而不是再次给出默认值。 - gdoron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接