2011-08-03 4 views
2

이의 콜백 함수 내에서 사용하여 $ (이) 어떻게 내가 할 수있는jQuery를 : 자기 정의의 jQuery 기능

$('#div').wider(function() { 
    console.log('div resizing done'); 

    // $(this) refers to window instead of $('#div') 
    $(this).css({background: '#f00'}); 
}); 

그래서 자기 정의의 jQuery 기능

$.fn.wider = function(callback) { 
    $(this).animate({width: 500}, function() { 
     callback(); 
    }); 
}; 

호출하는 기능입니다 아래의 클릭 기능과 같이 $ (this)를 사용 하시겠습니까?

$('#div').click(function() { 
    console.log('div clicked'); 

    // $(this) refers to $('#div') 
    $(this).css({background: '#f00'}); 
}); 

답변

2

Function.apply을 사용하십시오.

$.fn.wider = function(callback) { 
    $(this).animate({width: 500}, function() { 
     if (typeof callback === 'function') { 
      callback.apply(this); // <- here 
     } 
    }); 
}; 

약간 더 일반적인 구현 :

$.fn.wider = function(callback) { 
    var self = this; 
    $(this).animate({width: 500}, function() { 
     if (typeof callback === 'function') { 
      callback.apply(self); 
     } 
    }); 
}; 
+1

또는 ['Function.call' (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/call) :-P –

+0

Matt, 고맙습니다. 나는 여전히 jQuery에서 배울 것이 많다. : ( – pepsi600

+0

@pepsi는 jQuery가 아니라 JavaScript이다. –