本文介绍在Layui框架中为元素绑定事件的正确方法。核心要点包括必须预先加载element操作模块,否则绑定无效。推荐使用$(document).on(事件, 标识, function)的格式进行委托绑定,以支持动态生成的DOM元素。
Layui事件绑定前提与模块引用
需要注意的是,在开始操作前务必确保已经引入了element模块,如果遗漏这一步,后续的事件绑定将无法生效。
具体的绑定语法格式如下所示:
$(document).on绑定语法
使用jQuery的on方法,写法为:$(document).on(事件类型,选择器标识, function(){});
layui.use(['jquery', 'form', 'table', 'element'], function() {
var form = layui.form;
var table = layui.table;
var element = layui.element;
var $ = layui.$;
// form.render();
table.render({
elem: '#tableList',
// height: 315,
url: "{{route('admin.data')}}",
page: true, //开启分页
cols: [
[ //表头
{ field: 'id', title: 'ID', sort: true, fixed: 'left' },
{ field: 'name', title: '用户名' },
{ field: 'role', title: '角色', sort: true },
{
field: 'status',
title: '状态',
templet: function(d) {
return d.status == 0 ? '禁止' : '启用'
}
},
{ field: 'created_at', title: '创建时间' },
{
title: '操作',
// minWidth: 200,
templet: function(d) {
return '<button class="layui-btn layui-btn-xs " lay-filter="editF" id="edit" data-id="' + d.id + '">编辑</button>'
}
}
]
]
});
//绑定事件
$(document).on('click', '#edit', function(data) {
var id = $(this).attr('data-id');
});
});
以上就是关于在Layui环境下对元素进行事件绑定的完整介绍,希望上述内容能为您提供有效的参考,欢迎继续支持本站获取更多技术分享。