2014-10-25 3 views
0

jQuery 플러그인을 축소하고 스크립트의 맨 아래에 위치 시키면 스크립트 중간에 이라는 어딘가에서 함수가 호출됩니다.이로드됩니다.

이제 방법 1 오류가,

//method 1: red is not a function! 
/* 
(function($) { 
    $("#foo").red(); 
})(jQuery); 
*/ 

// method 2: this works 
jQuery(function() { 
    $("#foo").red(); 
}); 

// plugin 
(function($) { 
    $.fn.red = function() { 
     return $(this).css("color", "red"); 
    }; 
})(jQuery); 

누군가가이 두 방법의 차이를 설명 할 수

다음과 같은 간단한 코드를 참조하십시오 생성? 방법 1에서 오류의 원인은 무엇입니까?

$(function(){ 
    // code in here will be executed once the DOM is ready 
}); 

따라서 플러그인이 그렇게하지 않도록 "자체 등록"시간이 있습니다

답변

0

둘 사이의 주요 차이점은 DOM과 함께 코드를 포장으로 준비하는 두 번째 기다리는입니다 red이 함수가 아니라는 오류 메시지가 나타납니다. 당신이 jQuery를로드하고 이러한 모든 문제가 사라집니다 직후, 모든 플러그인을 등록 측면 참고로

(function($) { // $ is jQuery, prevents name collision with other frameworks 
    $(function(){ // Register the code to fire after the DOM is ready 
     $("#foo").red(); 
    }); 
})(jQuery); // Passes jQuery as a parameter so $ will be jQuery 

: 당신이 준비가 될 때까지 DOM을 기다리는 첫 번째 버전을 원하는 경우

, 이것을 사용 .