attr('defaultValue') is returning undefined using jQuery 1.6.3

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 23:37:42

Use prop():

$( '#q' ).prop( 'defaultValue' )

Live demo: http://jsfiddle.net/kHBsD/8/

You see, 'defaultValue' is not a content attribute (HTML attribute) as you can see for yourself if you look at your HTML source code. Instead, it's a property of the HTMLInputElement DOM element node.

See here: https://developer.mozilla.org/en/DOM/HTMLInputElement


Attributes exist in the HTML source code.
Properties exist in the DOM tree.

When the browser parses the HTML source code, the HTML <input> element is interpreted and a corresponding HTMLInputElement DOM node is created. This DOM element contains dozens of properties ('defaultValue' being one of them).


Here, I've refactored your code:

$( '.autoclear' ).
    focus( function () {
        if ( this.value === this.defaultValue ) {
            this.value = '';
            $( this ).removeClass( 'blur' ).addClass( 'focus' );
        }
    }).
    blur( function () {
        if ( this.value === '' ) { 
            this.value = this.defaultValue;
            $( this ).removeClass( 'focus' ).addClass( 'blur' );
        }
    });

Live demo: http://jsfiddle.net/kHBsD/9/

prop() is not necessary - you have the this reference, so you can just access the property directly. Also those hover handlers are not needed, just use a input:hover CSS rule.

var x=$('#q').prop('defaultValue');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!