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嗎?
參見[此的jsfiddle(http://jsfiddle.net/xTwCW/)的替代實現。你用地圖做的比較乾淨。 +1 –
@MichaelMior你的解決方案可行,但我更喜歡bdukes之一。我在測試過程中遇到了類似的解決方案,但我一直在尋找一種**正確的方式來實現它。 – skafandri
@bdukes效果很好,謝謝! – skafandri