Jquery实现即点即改

使用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);
                }
            }
        });
    });

注:如果代码遇到什么问题可以评论到下面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值