我有一个在我的项目中多次调用的函数:
function fillSelect(select) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Data.asmx/Status",
dataType: "json",
async: true,
success: function(data) {
$.each(data.d, function(i) {
select.append('<option value=' + data.d[i].value + '>' + data.d[i].name + '</option>');
});
},
error: function(result) {
alert("Error occured. Contact admin");
}
});
}
然后在我的代码中我这样使用:
fillSelect($('select#status1'));
fillSelect($('select#status2'));
fillSelect($('select#status3'));
我想做的是将我的函数转换为插件,所以我可以这样调用它:
$('select#status1, select#status2, select#status3').fillSelect();
使用http://starter.pixelgraphics.us/我生成了空模式:
(function($) {
$.ajaxSelect = function(el, select, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("ajaxSelect", base);
base.init = function() {
base.select = select;
base.options = $.extend({}, $.ajaxSelect.defaultOptions, options);
// Put your initialization code here
};
// Sample Function, Uncomment to use
// base.functionName = function(paramaters){
//
// };
// Run initializer
base.init();
};
$.ajaxSelect.defaultOptions = {
clear: false //append to select or replace current items
};
$.fn.ajaxSelect = function(select, options) {
return this.each(function() {
(new $.ajaxSelect(this, select, options));
});
};
})(jQuery);
但我不知道如何填写。
我想做的是调用服务器,然后填充与我输入参数一样多的选择项。
这么小的插件真的需要所有这些代码吗?
我知道可能有一些插件具有此功能,但我想创建自己的插件,只是为了了解更多:)