总结一点就是,有基础框架做任何事情都能顺利很多,感谢layui的共享!
layui作为前端页面的基础框架,写了几个小页面,过程中碰到的问题,做了几点零碎总结:
1、使用JS获取当前页面的URL的参数:
url:http://localhost:8200/jie/detail.html?tid=1
获取tid的参数值:
//js
var url_string = window.location.href;
var url = new URL(url_string);
var tid = url.searchParams.get("tid");
var page = url.searchParams.get("page") || 1;
2、给select动态添加item,layui不刷新:
js:
//重新渲染表单
renderForm = function(){
layui.use('form', function(){
var form = layui.form;//高版本建议把括号去掉,有的低版本,需要加()
form.render();
});
}
//动态添加option
for(let i = 0; i< res['data'].length; i++){
$("#topicType").append("<option value="+res['data'][i]['id']+">"+res['data'][i]['name']+"</option>");
}
renderForm();//表单重新渲染,要不然添加完显示不出来新的option
html:
<div class="layui-col-md3">
<label class="layui-form-label">主题分类</label>
<div class="layui-input-block">
<select lay-verify="required" name="topicType" id="topicType" lay-filter="column">
<option></option>
</select>
</div>
</div>
3、layui的缓存,session缓存和cookie缓存,一个页面关了就销毁,一个能持久化,可以根据场景选择页面数据共享的方法;
开始以为直接存储key,value,发现怎么存进去的都是空字符串{},原来value支持的是{key:"hello", value:"213"}的json结构,这个细节还是很容易踩的坑;
js:
saveTopicToCache = function(name, value){
var saveData = {key:name, value:value};
layui.sessionData('pub6_com_user_cache_topic', saveData);//把AJSON对象存储为字符串
}
loadTopicFromCache = function (name) {
var cacheUser = layui.sessionData('pub6_com_user_cache_topic');
return cacheUser[name] || {};
}
4、列表数据分页页签效果
html:
<div id="topic_page" style="text-align: center">
</div>
js:
//topic_page,根据返回的总条数计算总页码
var pageTotal = (res['data']['total']/pageSize)?(res['data']['total']/pageSize
+ ((res['data']['total']%pageSize)>0?1:0)):1;
var page_html=[
'<div class="laypage-main">',
'<a href="/jie/index.html?page=1" class="laypage-next">首页</a>',
'<span class="laypage-curr">1</span>',
'<span>…</span>',
'<a href="/jie/index.html?page='+pageTotal+'" class="laypage-last" title="尾页">尾页</a>',
'<a href="/jie/page/2/" class="laypage-next">下一页</a>',
'</div>'
];
console.log("pageTotal:"+pageTotal+",currPage:"+currPage);
var pageRealHtml = "";
pageRealHtml += page_html[0];
if (currPage >= 5){
pageRealHtml += page_html[1];
}
var start = 1;
var end = 0;
if (currPage < 5){
start = 1;
end = pageTotal;
}else{
start = currPage - 3;
end = pageTotal;
}
if (currPage == pageTotal){
start = (pageTotal > 4)?(pageTotal - 4):1 ;
end = pageTotal;
}
var index = 0;
for (var j=start; j<=end; j++){
if (index++ >= 5){
pageRealHtml += page_html[3];
pageRealHtml += page_html[4];
break;
}
if (j == currPage){
pageRealHtml += '<span class="laypage-curr">'+j+'</span>';
}else{
pageRealHtml += '<a href="/jie/index.html?page='+j+'" >'+j+'</a>';
}
}
pageRealHtml += page_html[6];
$("#topic_page").append(pageRealHtml);
6、异步提交后清空表单输入数据
form.on('submit(*)', function(data){
var action = $(data.form).attr('action'), button = $(data.elem);
fly.json(action, data.field, function(res){ //不需要跳转
$(data.form)[0].reset();
layui.form.render();
});