2011-12-18 7 views
3

우선 미안하지만 저는 정말 초보자입니다."this"in a plugin

jquery 플러그인에서 "this"를 정말로 이해하지 못하고 많이 찾고 있었지만 실제로 어떤 대답도 찾을 수 없었습니다.

여기 내 플러그인입니다

jQuery.fn.hoverPlugin = function(){ 

    var element = this; 

    $(element).animate({"opacity" : ".5"}); 


     $(element).hover(function(){ 
      $(element).stop().animate({"opacity" : "1"}); 
     }, function() { 
      $(element).stop().animate({"opacity" : ".5"}); 
     }); 
}; 

전화

$("img").hoverPlugin(); 

내 문제 (IM은 연습이 만들기)가 모든 이미지에 애니메이션 효과를 추가하는이 방법입니다. 페이지의 모든 이미지의 애니메이션이로드되지만 이미지 위에 마우스를 올리면 모두 움직입니다. 나는 간단한 방법

$("img").animate({"opacity" : ".5"}); 


     $("img").hover(function(){ 
      $(this).stop().animate({"opacity" : "1"}); 
     }, function() { 
      $(this).stop().animate({"opacity" : ".5"}); 
     }); 

에서 그것을 작성하는 경우

내가 원하는 방식으로 작동합니다.

그래서 숙련 된 개발자가 내 플러그인에 어떻게 이것을 설명 할 수 있을까요? 나는 정말로 행복 할 것이다.

당신을 감사합니다 .hoverPlugin 기능에 this$('img') 그것을 호출하는 데 사용 참조하고 있기 때문이다

답변

7

:

jQuery.fn.hoverPlugin = function(){ 
    var element = this; 

    $(element).animate({"opacity" : ".5"}); 

    $(element).hover(function(){ 
     $(element).stop().animate({"opacity" : "1"}); 
    }, function() { 
     $(element).stop().animate({"opacity" : ".5"}); 
    }); 
}; 
$(document).ready(function(){ 
    $("img").hoverPlugin(); 
}); 

http://jsfiddle.net/ww7gg/

당신이하려고하면 console가 열려, 당신이 볼 수와 그 내 말은.

그냥이로 변경하는 경우

:

$(element).hover(function(){ 
    $(this).stop().animate({"opacity" : "1"}); 
}, function() { 
    $(this).stop().animate({"opacity" : ".5"}); 
}); 

http://jsfiddle.net/ww7gg/1/

그것은 작동합니다.

그리고 이것은 더 :

jQuery.fn.hoverPlugin = function(){ 
    this 
     .animate({"opacity" : ".5"}) 
     .hover(function(){ 
      $(this).stop().animate({"opacity" : "1"}); 
     }, function() { 
      $(this).stop().animate({"opacity" : ".5"}); 
     }); 
}; 

당신은 단지 this 체인을 사용 element 필요가 없습니다. 플러그인에

http://jsfiddle.net/ww7gg/2/

+0

정말 큰 감사를 사용, 지금은 이해하고 내 질문에 찌르는 시간 주셔서 감사합니다 : JQuery와 요소 (들)의 컬렉션입니다. – Side

+0

문제 없으니 기꺼이 도와주세요. ':)' –

1

:

VAR 요소 =이; 당신의 도움에 대한

jQuery.fn.hoverPlugin = function(){ 
    var collection = this.animate({"opacity" : ".5"}); //Fade all elements to .5 opactiy. 

    collection.each(function() { 
     var element = this; // Single element from the collection 
      $el = $(element); //Create 1 jquery object and re-use it on the events. 

     $el 
      .hover(function(){ 
       $el.stop().animate({"opacity" : "1"}); 
      }, function() { 
       $el.stop().animate({"opacity" : ".5"}); 
      }); 
    }); 

}; 
1
jQuery.fn.hoverPlugin = function(){ 

    var element = this; //this is already wrapped as jquery object e.g it will refer to $("img") in your case 

    element.animate({"opacity" : ".5"}); 


     element.hover(function(){ 
      element.stop(true,true).animate({"opacity" : "1"}); 
     }, function() { 
      element.stop().animate({"opacity" : ".5"}); 
     }); 
}; 

$("img").hoverPlugin();