本篇文章給大家帶來的內容是關於基於layui實現動態添加下拉選擇框的模組,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
這星期剛接觸layui,看到她的模組化,於是動手弄了個select選擇拉練習不多說下面貼代碼,不足地方請指出
/** * 基於layui擴充一個動態添加下拉選擇框模組 */layui.define(['form', 'jquery'], function(exports) { //提示:模組也可以依賴其它模組,如:layui.define('layer', callback);var form = layui.form;var jquery = layui.jquery;function selectDropDown() {/** * 產生uuid * @param {len} 長度 * @param {radix} 進位 如 2,10,16 */this.uuid = function(len, radix) {var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid = [],i;radix = radix || chars.length;if(len) {// Compact formfor(i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];} else {// rfc4122, version 4 formvar r;// rfc4122 requires these charactersuuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';uuid[14] = '4';// Fill in random data. At i==19 set the high bits of clock sequence as// per rfc4122, sec. 4.1.5for(i = 0; i < 36; i++) {if(!uuid[i]) {r = 0 | Math.random() * 16;uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];}}}return uuid.join('');}this.init = function(opts) {opts = jQuery.extend({target: '',options: [],onSelect:function(){}}, opts || {});var uuid = this.uuid(8, 16);var target = jquery(opts.target);target.addClass('layui-form');target.attr('lay-filter', "select"+uuid);var original = target.attr('data-original');var currentValue = target.attr('data-value');var domSelect = jquery('<select/>');domSelect.attr('lay-filter', "domSelect"+uuid);for(var i = 0; i < opts.options.length; i++) {var o = opts.options[i];var domOption = jquery('<option/>');domOption.text(o.text);domOption.val(o.value);if(original === o.value.toString()) {domOption.attr('selected', 'selected');}domSelect.append(domOption);}target.append(domSelect);form.on("select(domSelect"+uuid+")", function(data) {target.attr('data-value',data.value);opts.onSelect(data);//下拉選中後回調});form.render('select', "select"+uuid);//重新整理渲染}}//輸出select介面exports('select', selectDropDown);});
使用時
html 部分
<div style="width: 300px; margin-right: 20px;" id="sex" data-original="女" data-value="女"></div> data-original 初始值 data-value 下拉選中的值jslayui.use(['select'], function() { var select = layui.select; var sexOptions = [ {text:'男',value:"男"}, {text:'女',value:"女"}];var sexSelect = new select();sexSelect.init({target:'#sex',options:sexOptions});});