thinkphp5使用ajax双击td标签进行修改内容

前端代码:

<table class="table table-border table-bordered table-bg table-hover table-sort table-responsive">
			<thead>
				<tr class="text-c">
					<th width="80">id</th>
					<th width="60">时间</th>
					<th width="120">剩余数量(双击修改)</th>
				</tr>
			</thead>
			<tbody class="tbody">
				{volist name='data' id='v'}
					<tr class="text-c">
						<td style="padding-top: 20px;">{$v.id}</td>
						<td style="padding-top: 20px;">{$v.time}</td>
						<td id="{$v.id}" style="padding-top: 20px;">{$v.num}</td>
					</tr>
				{/volist}
			</tbody>
		</table>

这里因为是使用了thinkphp5的模板,将查询的数据使用了volist在前端页面循环输出

最重要的js代码

$(document).ready(function() {
	// 获取每一行第三个td
    var numId=$(".tbody tr td:nth-child(3)").each(function(){
            });
	//当双击td时触发
    numId.dblclick(function(){
        var tdIns=$(this);
        var tdpar=$(this).parents("tr");

        var tdId=$(this).attr("id");
        tdpar.css("backgroundColor","white");

        if(tdIns.children("input").length>0){
            return false;
        }

        var text = $(this).html();
        var inputIns = $("<input  type='number'/>"); //需要插入的输入框代码 
        inputIns.width(tdIns.width);//设置input与td宽度一致 
        inputIns.height("30px");
        inputIns.val(tdIns.html());//将本来单元格td内容copy到插入的文本框input中
        
        tdIns.html(""); //删除原来单元格td内容 

        inputIns.appendTo(tdIns).focus().select(); //将需要插入的输入框代码插入dom节点中 

        inputIns.click(function(){
            return false;
        }); 
        //处理Enter和Esc事件   
        inputIns.blur(function(){   
        var inputText = $(this).val();  
        tdIns.html(inputText);  
        tdpar.css("background-color","white");
			$.ajax({
				type:"post",
				url:'edit',
				data:{id:tdId,num:tdIns.html()},//这里data传递过去id和num两个值
				success:function(msg){
				if(msg.state == 1){
						alert(msg.msg);
						history.go(0);
					}
					if(msg.state == 2){
						alert(msg.msg);
						history.go(0);
					}
				}
			});
        }); 
		
    });
});

控制器代码

public function edit($id,$num){
		$data = [
			'num' => $num
		];
		$upd = Db::name('ticket')->where('id',$id)->update($data);
		if($upd){
			$msg['msg'] = '操作成功';
			$msg['state'] = 1;
			return json($msg);
		}else{
			$msg['msg'] = '操作失败';
			$msg['state'] = 2;
			return json($msg);
		}
	}

这就完成了双击td标签来进行修改原来的内容了
修改完成后再使用ajax传给后台进行操作
后台更新完数据后再返回给前端
前端可以根据返回的信息来判定是否修改成功

发布了22 篇原创文章 · 获赞 2 · 访问量 427

猜你喜欢

转载自blog.csdn.net/jianchenn/article/details/105730660