In the process of using layui, there are several methods that need to be referenced by multiple js, so I customized a layui module according to the document, and the implementation process is as follows (recommended: layui usage tutorial)
First define a module
//定义模块 layui.define(['form'], function(exports){ var form = layui.form; //只有执行了这一步,部分表单元素才会自动修饰成功 var $ = layui.$; var obj = { changeParentPlace: function (parentId,tagId,levelPlace) { $.ajax({ url:ctx + '/base/place/changeParentPlace', type:'get', data:{ parentId:parentId }, dataType:'json', success:function (data) { $("#" + tagId).empty(); $("#" + tagId).append('<option value="">请选择</option>'); if(data.result != null && data.result.length != 0) { $.each(data.result,function(i,place) { if(levelPlace == place.name) { $("#" + tagId).append('<option selected value="'+place.id+'">'+place.name+'</option>') }else { $("#" + tagId).append('<option value="'+place.id+'">'+place.name+'</option>') } }) } form.render('select'); //刷新select选择框渲染 } }) } } //输出模块 exports('common', obj); });
Define the method using layui.define
The first parameter in define can load some built-in layers in layui To use the module, some public methods are defined in the second callback method
The first parameter of exports is the name of this module, and the second parameter is an object in which these three methods are defined.
Set the module
//设置模块 layui.config({ base: ctx + '/js/app/modules/' //假设这是你存放拓展模块的根目录 }).extend({ //设定模块别名 common:'common' });
Define the module using layui.config
base defines the directory where the js that defines the module is located
common is the alias of the setting, ' common' is the file name in the directory (.js is automatically added)
Calling module
layui.use(['common'], function(){ var common = layui.common; common.changeParentPlace($("#firstLevelId").val(),'secondLevelId'); });
First use the common module, and the calling code is as above common.changeParentPlace($("#firstLevelId") .val(),'secondLevelId'); is the same as using the built-in module
The above is the detailed content of layui defines a module and uses the instance. For more information, please follow other related articles on the PHP Chinese website!