Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

jquery function val() is not equivalent to "$(this).value="?

When I try to set a text input to blank (when clicked) using $(this).value="", this does not work. I have to use $(this).val('').

Why? What is the difference? What is the mechanism behind the val function in jQuery?

$(document).ready(function() {
    $('#user_name').focus(function(){
        $(this).val('');
    });
});
// error code: not working...
$(document).ready(function() {
    $('#user_name').focus(function(){
        $(this).value='';
    });
});
question from:https://stackoverflow.com/questions/4524702/jquery-function-val-is-not-equivalent-to-this-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want:

this.value = ''; // straight JS, no jQuery

or

$(this).val(''); // jQuery

With $(this).value = '' you're assigning an empty string as the value property of the jQuery object that wraps this -- not the value of this itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...