正常情况下,有一种思路是双击事件触发增加一个input,将原值附给input,然后失去焦点时判断是否更改,不更改恢复原值,更改则用后台交互更新数据库并更改页面内容,参考代码(摘):
$(function(){
$('#tableId').on('dblclick','td',function(){
var oldVal = $(this).text;
var input = "<input type="text" id="tempId" value='"+oldVal+"'>";
$(this).text('');
$(this).append(input);
$('#tempId').focus();
$('#tempId').blur(function(){
if($(this).val()!=''){
oldVal = $(this).val();
}
$(this).closest('td').text(oldVal);
})
})
})
但此时双击出现输入框后再次双击,输入框中的原值就消失了,并且oldval变成了空,如果此时失去焦点,原内容就被修改没了,这样没双击一次创建一个输入框,这时需要加一个属性控制input的生成次数.
HTML代码:
<table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black ">
<thead>
<tr>
<th>ID</th>
<th>类别</th>
<th>父级类别</th>
<th>路径</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for i in data %}
<tr class="even gradeC">
<td>{{ i.id }}</td>
<td>{{ i.cat }}<span class="tname" isclick="0">{{i.name}}</span></td>
<td>{{ i.pname }}</td>
<td>{{ i.path }}</td>
<td>
<div class="tpl-table-black-operation">
<a href="javascript:;">
<i class="am-icon-pencil"></i> 编辑
</a>
<a href="javascript:;" class="tpl-table-black-operation-del">
<i class="am-icon-trash"></i> 删除
</a>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
JavaScript代码:
<script>
function typenameedit($this){
$this.attr('isclick','1')
tname = $this.text()
inp = $('<input type="text" value="'+tname+'" style="color:black;">')
$this.html(inp)
inp.select()
inp.blur(function(){
newname = $(this).val()
if(newname == tname){
$this.text(tname)
}else{
id = $this.parents('tr').find('td:first').text()
$.get('{% url 'myadmin_typeedit' %}',{'id':id,'name':newname},function(data){
if (data['code'] == 0) {
$this.text(newname)
alert(data['msg'])
}else{
$this.text(tname)
alert(data['msg'])
}
},'json')
}
$this.attr('isclick','0')
})
}
$('.tname').dblclick(function(){
var num = $(this).attr('isclick')
if(num == '0'){
typenameedit($(this))
}
})
</script>
Django后台代码:
def edit(request):
try:
id = request.GET.get ('id')
name = request.GET.get ('name')
obj = models.Booktype.objects.get (id=id)
obj.name = name
obj.save ()
return JsonResponse ({'code': 0,'msg': "修改成功"})
except:
return JsonResponse ({'code': 1,'msg': "修改失败"})