if ($('#selector').length == 0) doesn't work in IE7 and IE8
Here is my jquery code:
$(document).ready(function() {
if ($('#login').length == 0) {
$('#login').css('background', "url('/css/login-bg.gif') 2px center no-repeat");
}
if ($('#password').length == 0) {
$('#password').css('background', "url('/css/password-bg.gif') 2px center no-repeat");
}
$('#login').focus(function() {
$(this).css('background', 'transparent');
});
$('#password').focus(function() {
$(this).css('background', 'transparent');
});
});
It works in Firefox but not in IE7 or IE8. Why?
The purpose of this code: It is supposed to display a user friendly text inside sign in form so users know what to fill in username and password input fields. This is important because input fields don't have labels (I k开发者_运维问答now... but client just does not want labels there).
The if ($('#selector').length == 0) condition is there because if user saves his/her username and password in the browser, the browser will fill in the saved values automatically, so it makes sure the background image doesn't overlap them.
You should be using:
if($('#selector').val() == '')
instead of
if ($('#selector').length == 0)
$('#selector').length
will only tell you how many elements were matched, not the length of the value of the selected elements. See here: http://api.jquery.com/length/
精彩评论