$.fn.iOSPicker = function (options) {
var defaults = {
data: [],
onSelect: function () { }
};
var settings = $.extend({}, defaults, options);
var picker = $(this);
var pickerOverlay = $('');
var pickerContainer = $('');
var pickerTitle = $('');
var pickerOK = $('');
var pickerCancel = $('');
var pickerList = $('
');
// 處理數(shù)據(jù)
function processData() {
pickerList.empty();
var data = settings.data;
for (var i = 0; i< data.length; i++) {
var li = $('');
li.text(data[i]);
pickerList.append(li);
}
}
// 彈出選擇器
function showPicker() {
processData();
// 添加遮罩層和容器
$('body').append(pickerOverlay);
$('body').append(pickerContainer);
// 設(shè)置標(biāo)題和按鈕
pickerTitle.text(settings.title);
pickerOK.text(settings.okText);
pickerCancel.text(settings.cancelText);
// 綁定按鈕事件
pickerOK.on('click', function () {
var selectedItem = pickerList.find('.selected').eq(0);
var index = pickerList.find('li').index(selectedItem);
var value = selectedItem.text();
settings.onSelect(index, value);
hidePicker();
});
pickerCancel.on('click', hidePicker);
// 添加標(biāo)題和按鈕
pickerContainer.append(pickerTitle);
pickerContainer.append(pickerOK);
pickerContainer.append(pickerCancel);
// 添加列表
pickerContainer.append(pickerList);
// 綁定選擇事件
pickerList.on('click', 'li', function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
// 顯示選擇器
pickerOverlay.show();
pickerContainer.show();
}
// 隱藏選擇器
function hidePicker() {
pickerOverlay.hide();
pickerContainer.hide();
}
// 綁定點(diǎn)擊事件
picker.on('touchstart click', function () {
showPicker();
});
return this;
};