jsGrid分页后项绑定的点击事件失效问题求助
解决jsGrid分页后图片点击事件失效的问题
问题原因
你当前直接给.recordimage元素绑定点击事件,但分页切换后生成的新图片是动态创建的,初始化时的事件绑定只会作用于当时已存在的元素,后续动态生成的元素无法触发绑定的事件,导致点击失效。
解决方法
使用事件委托,把点击事件绑定到静态存在的父容器(比如#patientsgrid)上,通过监听子元素的点击来触发逻辑,这样不管元素是初始化时就有还是后续动态生成的,都能响应事件。同时建议用标准的data-*属性存储uuid,替代自定义的uuid属性,更符合HTML规范。
修改后的代码如下:
function fillpatientsGrid(){ $("#patientsgrid").jsGrid({ width: "90%", height: "600px" , sorting: true, paging: true, pageSize: 12, data: patientsData, controller: { loadData: function(filter) { console.log("loadData"); }, }, fields: [ { name: "name", title:"Name",type: "text",readOnly: true,align:"center",width: 120 }, { name: "DOB",title:"DOB",type: "text",align:"center", width: 70, sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }}, { name: "Gender", title:"Gender",type: "text", align:"center",width: 70}, { name: "Age",title:"Age", type: "number", align:"center", width: 70} , { name: "LastReportedByDate", title:"Last Visit",type: "text",align:"center", width: 70}, { name: "createdBy", title:"Created By",type: "text",align:"center", width: 70}, { name: "uuid", title:"Patient Record",type: "text",align:"center", width: 100,itemTemplate: function(value, item) { // 修正属性引号,改用data-uuid存储uuid值 return '<img src="/images/patient-record.png" class="recordimage" width="30" height="30" data-uuid="'+value+'">'; }} ] }); // 使用事件委托,绑定到父容器#patientsgrid上 $("#patientsgrid").on('click', '.recordimage', function(){ // 通过data()方法获取data-uuid的值 var uuid = $(this).data('uuid'); window.location.href = '/patientrecord/?useruuid='+uuid; }) }
关键改动说明
- 事件绑定改为
$("#patientsgrid").on('click', '.recordimage', function(){...}):父容器是初始化时就存在的静态元素,通过它监听子元素的点击事件,动态生成的.recordimage元素也能触发。 itemTemplate里把uuid='+value+'改成data-uuid="'+value+'":使用HTML标准的自定义数据属性,避免潜在的属性冲突,同时可以通过jQuery的data()方法更安全地获取值。
内容的提问来源于stack exchange,提问作者Webdev
相关产品推荐
相关产品推荐

