2012-05-10 18 views
1

我正在寫一個jQuery插件,主要目的是採取選擇元素,並基於它創建一個新的組件,到目前爲止,我只想要一個空div來替代選擇:
jQuery插件chainability

(function($){ 
    $.fancySelect = {version:'1.0'}; 
    var methods = { 
     init: function(options){ 
      return this.each(function(){     
       var div = $('<div></div>'); 
       $(this).replaceWith(div); 
      }); 
     } 
    }; 
    $.fn.fancySelect = function(method){ 
     if (methods[method]){//call a method 
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else { 
      return methods.init.apply(this, arguments); 
     } 
    } 
})(jQuery); 

試圖測試,我做一個簡單的選擇:

<select id="sss"></select> 

當我打電話:

$('#sss').fancySelect(); 

選擇正確替換爲空Div,這是好的。
但現在,測試chainability的時候,我嘗試:

$('#sss').fancySelect().append('<span>new text</span>'); 

但我的新的div保持爲空
所以,我想:

console.log($('#sss').fancySelect()); 

在螢火蟲我得到:

[select#sss] 

意味着插件正在返回舊的選擇。

我嘗試添加

return $(this); 

$(this).replaceWith(div); 
在我的插件代碼

,但什麼都沒有改變!

你能告訴我該怎麼做才能讓我的插件返回新創建的Div嗎?

回答

3

當您返回this.each時,您將返回原始jQuery選擇,即使您已替換了這些元素,該選擇仍未更改。除了使用each的,使用map調整返回什麼:

return this.map(function(){     
    var div = $('<div></div>'); 
    $(this).replaceWith(div); 
    return div; 
}); 
+0

參見[此的jsfiddle(http://jsfiddle.net/xTwCW/)的替代實現。你用地圖做的比較乾淨。 +1 –

+0

@MichaelMior你的解決方案可行,但我更喜歡bdukes之一。我在測試過程中遇到了類似的解決方案,但我一直在尋找一種**正確的方式來實現它。 – skafandri

+0

@bdukes效果很好,謝謝! – skafandri