使用Jquery实现即点即改功能
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<span class="old_val">测试</span>
<input type="hidden" class="new_val">
</body>
</html>
JS代码:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(".old_val").click(function(){
var vo = $(this).text(); //获取原来的值
$(this).hide();
$(this).next().attr('type', 'text').val(vo).focus().show();
});
$(".new_val").blur(function(){
var _this = $(this); //表示当前元素
var new_val = $(this).val(); //新的值
var old_val = $(this).prev().text(); //旧的值
//判断 --- 与未修改的值相等
if(new_val === old_val){
$(this).prop('type', 'hidden');
$(this).prev().show();
return false;
}
//新的值不能为空 -- 这个看情况进行判断,不一定就不能为空
if(new_val === ''){
alert('修改后不能为空');
$(this).prop('type', 'hidden');
$(this).prev().show();
return false;
}
$.ajax({
type: "get", //请求方式,简单的修改的话,get就可以
url: "?r=fields/update_field", //请求地址
data: {'new_val':new_val,}, //往后台传的值
dataType: "json",
success:function(msg){
if(msg === '0'){
alert('修改失败!');
$(this).prop('type', 'hidden');
$(this).prev().show();
return false;
}
if(msg === '1'){
_this.prop('type', 'hidden');
_this.prev().show().text(new_val);
}
}
});
});