使用jQuery获取输入的默认值

Bat*_*Dor 17 html javascript jquery input default-value

$(".box_yazi2").each(function () {
    var default_value = this.value;
    $(this).css('color', '#555'); // this could be in the style sheet instead
    $(this).focus(function () {
        if (this.value == default_value) {
            this.value = '';
            $(this).css('color', '#000');
        }
    });
    $(this).blur(function () {
        if (this.value == '') {
            $(this).css('color', '#555');
            this.value = default_value;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

这个输入默认值的函数在FF中不起作用,但在IE中完全有效,并且当然输入本身如下所示:

<input type="text" class="box_yazi2" id="konu" name="konu" value="Bo?" />
Run Code Online (Sandbox Code Playgroud)

Sal*_*n A 74

只需使用该defaultValue属性:

var default_value = $(this).prop("defaultValue");
Run Code Online (Sandbox Code Playgroud)

要么:

var default_value = this.defaultValue;
Run Code Online (Sandbox Code Playgroud)

  • defaultValue是一个可通过JavaScript访问的内置属性.对于input [type = text],它包含input元素的原始值...加载页面时出现的值. (19认同)
  • @crazy:请参阅[DOM级别2规范中描述的接口HTMLInputElement](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-6043025)和[MDN上的HTMLInputElement] (https://developer.mozilla.org/en/DOM/HTMLInputElement).其他有趣的属性是defaultChecked,defaultSelected用于radio/checkboxes和select元素中的选项. (5认同)
  • HTML中的属性和属性之间存在差异.要获取defaultValue或defaultChecked,我们应该使用.prop()方法.在jQuery.com上有一个很好的解释:http://api.jquery.com/prop/ (3认同)

And*_*air 9

解决方案非常简单; 你});的代码中有额外的内容(感谢@ Box9).

我鼓励你重用变量而不是创建几十个jQuery对象.

我已经改变了你的例子background-color但它会起作用.

$('.box_yazi2').each(function(index, element) {
    var $element = $(element);
    var defaultValue = $element.val();
    $element.css('background-color', '#555555');
    $element.focus(function() {
        var actualValue = $element.val();
        if (actualValue == defaultValue) {
            $element.val('');
            $element.css('background-color', '#3399FF');
        }
    });
    $element.blur(function() {
        var actualValue = $element.val();
        if (!actualValue) {
            $element.val(defaultValue);
            $element.css('background-color', '#555555');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

演示