开发者

jQuery: using $(this) inside a callback function of a self-defined jQuery function

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);
        }
    });
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜