Jeditable是一个轻量级的jQuery插件,它允许您将页面上的任何元素变成可编辑的字段。默认情况下,Jeditable每次只处理单个字段的编辑和保存,但通过一些技巧可以实现多个字段的同时编辑和批量保存。
$('.editable').editable(function(value, settings) {
// 获取所有可编辑字段的值
var data = {};
$('.editable').each(function() {
data[$(this).attr('id')] = $(this).text();
});
// 发送AJAX请求
return $.ajax({
url: '/save-multiple',
type: 'POST',
data: data,
dataType: 'json'
}).then(function(response) {
return response.value; // 返回更新后的值
});
}, {
type: 'text',
submit: '保存',
cancel: '取消',
tooltip: '点击编辑',
onblur: 'submit',
width: 'auto'
});
// 初始化所有可编辑字段
$('.editable').editable(function(value, settings) {
// 这个函数会在单个字段提交时被调用
// 但我们在这里不做实际保存,而是标记为需要保存
$(this).data('changed', true);
return value; // 立即返回新值而不保存
}, {
onsubmit: function(settings, original) {
// 阻止默认的提交行为
return false;
},
onreset: function(settings, original) {
// 阻止默认的重置行为
return false;
}
});
// 添加保存按钮
$('#save-all').click(function() {
var data = {};
$('.editable').each(function() {
if ($(this).data('changed')) {
data[$(this).attr('id')] = $(this).text();
$(this).data('changed', false);
}
});
if (Object.keys(data).length > 0) {
$.post('/save-multiple', data, function(response) {
alert('保存成功');
});
} else {
alert('没有更改需要保存');
}
});
// 为每行添加编辑按钮
$('.edit-row').click(function() {
var row = $(this).closest('tr');
row.find('.editable').editable('enable');
$(this).hide();
row.find('.save-row').show();
});
// 为每行添加保存按钮
$('.save-row').click(function() {
var row = $(this).closest('tr');
var data = {
id: row.data('id')
};
row.find('.editable').each(function() {
data[$(this).data('field')] = $(this).text();
$(this).editable('disable');
});
$.post('/save-row', data, function(response) {
$(this).hide();
row.find('.edit-row').show();
}.bind(this));
});
问题1:编辑一个字段后,其他字段的编辑状态丢失
原因:默认情况下,Jeditable会为每个字段创建独立的编辑表单
解决方案:使用方法二或方法三,或者自定义Jeditable的显示/隐藏逻辑
问题2:如何验证多个字段的数据
解决方案:在保存前添加验证逻辑:
$('#save-all').click(function() {
var isValid = true;
$('.editable').each(function() {
if (!validateField($(this).attr('id'), $(this).text())) {
isValid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
if (isValid) {
// 执行保存逻辑
}
});
function validateField(fieldId, value) {
// 添加你的验证逻辑
return true;
}
问题3:如何实现部分保存(只保存已修改的字段)
解决方案:使用方法二中的标记技术,或者在服务器端比较新旧值
通过以上方法,您可以灵活地实现Jeditable的多字段编辑和批量保存功能,根据具体需求选择最适合的实现方式。
没有搜到相关的文章