客户端代码
两个事件,利用双击获取焦点,失去焦点后触发ajax请求
//修改任务名称,双击任务时触发
taskBox.on('dblclick', 'label', function () {
//让任务处于编辑状态 this是label相当于拿到ul给他添加类editing
$(this).parent().parent().addClass('editing');
//将任务名称显示在文本框中
$(this).parent().siblings('input').val($(this).text());
//让文本框获得焦点(否则还得点一下才能输入)
$(this).parent().siblings('input').focus();
})
//修改任务名称,当文本框失去焦点
taskBox.on('blur', '.edit', function () {
//拿到新输入任务名称
var TaskName = $(this).val();
//编辑任务的id attr拿到属性值
var id = $(this).siblings().find('button').attr('data-id');
//通过ajax向服务器发送请求,修改任务名称
$.ajax({
url: '/todo/modifyTask',
type: 'post',
data: JSON.stringify({
_id: id,
title: TaskName
}),
contentType: 'application/json',
success: function (response) {
//走到成功函数里说明服务端修改成功,接下来我们修改客户端
//根据id找到当前修改的任务
var task = taskAry.find(item => item._id == id);
//修改任务名称
task.title = response.title;
//将任务数组中任务同步到页面中
render();
}
})
})
服务端代码
// 修改任务
todoRouter.post('/modifyTask', async (req, res) => {
// 执行修改操作
const task = await Task.findOneAndUpdate({_id: req.body._id}, _.pick(req.body, ['title', 'completed']),{new: true})
// 响应
res.send(task);
});
问题
这里传参传递title,而我写的name,导致服务器端接收不到该更新参数,客
户端拿到的值也没有更新,造成只要一离开焦点任务名称就会复原。