This is the self-defined jQuery function
$.fn.wider = function(callback) {
$(this).animate({width: 500}, function() {
callback();
});
};
Call the function
$('#div').wider(function() {
console.log('div resizing done');
// $(this) refers to window instead of $('#div')
$(this).css({background: '#f00'});
});
so how can I use $(this) like in the click funciton below?
$('#div').clic开发者_开发知识库k(function() {
console.log('div clicked');
// $(this) refers to $('#div')
$(this).css({background: '#f00'});
});
Use Function.apply
.
$.fn.wider = function(callback) {
$(this).animate({width: 500}, function() {
if (typeof callback === 'function') {
callback.apply(this); // <- here
}
});
};
A slightly more general implementation:
$.fn.wider = function(callback) {
var self = this;
$(this).animate({width: 500}, function() {
if (typeof callback === 'function') {
callback.apply(self);
}
});
};
精彩评论