开发者

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

开发者 https://www.devze.com 2023-03-26 05:20 出处:网络
This is the self-defined jQuery function $.fn.wider = function(callback) { $(this).animate({width: 500}, 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

精彩评论

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