Jquery: passing variable to the next chained function, is this the correct way?
I want to know if this is correct.
$('.myfilter').focus(function(){
var length = $(this).val().length;
if (length == 0) {
dosomething
}
}).blur(function(length){
if (length == 0) {
dowhate开发者_运维百科ver
}
})
Above i've simplified my code, im just checking if length == 0
on focus and blur for my input. notice how I declared length
in focus, but not in blur, but i added the variable name inside .blur(function(length){
. Is this the better way to get length
accessible in .blur
without having to re-declare var length = $(this).val().length;
in .blur?
as opposed to this:
$('.myfilter').focus(function(){
var length = $(this).val().length;
if (length == 0) {
dosomething
}
})
$('.myfilter').blur(function(length){
var length = $(this).val().length;
if (length == 0) {
dowhatever
}
})
the first code block is the better way to do this?
How about not declaring any variables at all... :)
$('.myfilter').focus(function() {
if ( this.value.length === 0 ) {
dosomething();
}
}).blur(function(length) {
if ( this.value.length === 0 ) {
dowhatever();
}
});
Also, this:
$('.myfilter').bind('focus blur', function(e) {
if ( this.value.length === 0 ) {
e.type === 'focus' ? dosomething() : dowhatever();
}
});
Using variables
Usually you want to use a variable if you need to use a certain value multiple times. However, in this case, you need the this.value.length
value only once (in the if-header). Therefore, you can directly inject this value inside the if-header.
$(this) vs this
In order to understand when to use which, you need to understand the difference between a DOM element object and a jQuery object. A jQuery object is a wrapper object which contains zero or more DOM element objects (like an array). It is important to understand that you can only call jQuery methods (like .addClass()
) on jQuery objects, not DOM elements directly.
Inside event handler functions, the this
value refers to the DOM element at which the event fired. Now, if you want to call jQuery methods on that DOM element, you need to wrap that DOM element inside a jQuery object - you do this by writing $(this)
.
$(this).addClass('selected'); // works fine
this.addClass('selected'); // throws Error
What I would normally do, if you don't want to recapture length
, is store length
in a property on this
and then read it in the blur
event, like so:
$('.myfilter').focus(function(){
this.val_length = $(this).val().length;
if (this.val_length == 0) {
dosomething
}
}).blur(function(){
if (this.val_length == 0) {
dowhatever
}
})
The first code block won't work - the passed parameter to .blur()
will actually be the event that triggered the blur call.
Also note that there's no need to use jQuery to obtain the value, it's a direct property of this
(for input elements):
$('.myfilter').blur(function(ev) {
if (this.value.length === 0) {
// dowhatever
}
});
精彩评论