2011-02-05 7 views
2

にこのコードを追加することができます私は、これは、クラス=「プラグイン」と私のオリジナルのマークアップですは、私は同じプラグイン

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

このマークアップの任意.pluginを取り、それに追加します(プラグイン可能と呼ばれる)のプラグインを持っています。 JSで

<div class="plugin"></div> 
<div class="plugin"></div> 
<div class="plugin"></div> 

、私は上記の<span>のhtmlを追加し、それがこの

<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> 

ように見えます。これは、すべてのプラグインですした$('.plugin').pluggable();呼び出すように(このHTMLを追加)し、プラグイン自体は単純ですこの

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

しかし、私が本当にやろうとしていることは、私はそれを直すその背景色を変更したい、クラス.colorableとのスパンがクリックされた場合、それ以降ということですd。私はこの

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

のようにjQueryを使ってこれを行うことができますが、そこには、全体の動作は、自己が含まれるように同じプラグインに含まれているこのコードを持っている方法です。プラグインが動作する元の要素はクラス.pluginですが、最終的に色付けされる要素は新しいスパンマークアップで、追加されるのは.colorableです。しかし、私は、この操作のためのすべてのコードを単一のプラグイン/ファイルに保存したいと思います。出来ますか?

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

答えて

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); 

あなたが好きなあなたはこの1つを使用することができます

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); 

Doが、前にDOMに要素を追加します。