2011-02-05 2 views
2

나는 어떤 .plugin 걸리는 플러그인 (pluggable)이 있고이 마크 업을 추가합니다.이 코드를 동일한 플러그인에 추가 할 수 있습니까?

<span class="colorable">color me</span> 

이것은 class = "plugin"인 원래의 마크 업입니다.

<div class="plugin"></div> 
<div class="plugin"></div> 
<div class="plugin"></div> 
<div class="plugin"></div> 
<div class="plugin"></div> 
<div class="plugin"></div> 
js에서 위의 <span> html을 추가 한 $('.plugin').pluggable();를 호출하여 다음과 같이 만듭니다.

<div class="plugin"><span class="colorable">color me</span></div> 
<div class="plugin"><span class="colorable">color me</span></div> 
<div class="plugin"><span class="colorable">color me</span></div> 

이것은 모든 플러그인입니다 (이 html 추가) 그리고 플러그인 자체는 이

(function($){ 
    $.fn.pluggable = function() {  
     return this.each(function() { 
      $(this).html('<span class="colorable">color me</span>'); 
     }); 
    }; 
})(jQuery); 

하지만 실제로 그 일을하려고하는 것은 class .colorable 클래스가 클릭 될 때 그 배경색을 빨간색으로 변경하기를 원한다는 것입니다. 나는이 작업을 jquery

$('.colorable').click(function(){ 
    $this.css("background-color", "orange"); 
}); 

같은 할 수 있지만 전체 작업을 자체 포함되어 있으므로이 코드를 동일한 플러그 인 포함 된 방법입니다. 나는 플러그인이 작동하는 원래 요소가 클래스 .plugin이기 때문에 궁금해 지지만, 결국 색칠 된 요소는 .colorable이 추가 된 새로운 span 마크 업입니다. 하지만이 작업에 대한 모든 코드를 단일 플러그인/파일에 보관하고 싶습니다. 가능한가?

답변

1

당신은 .colorable.click 처리기를 바인딩 할 수는 삽입 한 번에 걸쳐 이것을 jquery와 함께 사용하여 코드를 구조화하는 것이 좋습니다.

(function($){ 
    $.fn.pluggable = function() {  
     return this.each(function() { 

      // Create the element 
      var spanElement = document.createElement('span'); 
      // Set the class 
      spanEleement.className = 'colorable'; 
      spanElement.appendChild(document.createTextNode('color me')); 
      // Add the event using jQuery 
      $(spanElement).click(function() { 
       $(this).css('background-color', 'orange'); 
      }); 
      // Append it using jQuery function 
      $(this).append(spanElement); 
      // native function for this would be element.appendChild() 

     });    
})(jQuery); 

희망이 있습니다. 당신이 원하는대로 당신이 하나를 사용할 수 있습니다

0

jQuery를 새로운 요소 (document.createElement('tagName'))을 만들기위한 DOM 함수를 대체하지 않습니다 그리고 방법을 배울 매우 유용합니다

0

,

(function ($) { 
$.fn.pluggable = function() { 
    return this.each(function() { 
     var span = $('<span class="colorable">color me</span>'); 
     span.click(function(){ 
       $(this).css("background-color", "orange"); 
     }); 
     $(this).append(span); 
    }); 
}; 
})(jQuery); 

음주 전에 DOM에 요소를 추가합니다.

관련 문제