JQuery 表格td双击可编辑

JQuery 表格td双击可编辑


版本说明:jquery V3.5.1、Bootstrap V5.0.0


双击编辑的原理: JS监听到双击事件后,获取当前元素(td)的InnerText,然后将它放到一个input中再塞回td。input失去焦点后,再将修改后的值塞回到td就可以了。

代码

HTML:

<table class="table">
  <thead>
    <tr>
      <th class="cell">姓名</th>
      <th class="cell">电话</th>
      <th class="cell">省份</th>
      <th class="cell">城市</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <!--    支持双击修改的td,包含类名db-click-->
      <td class="cell db-click">ABC</td>
      <td class="cell db-click">12345678910</td>
      <td class="cell db-click">江苏</td>
      <td class="cell db-click">徐州</td>
    </tr>
  </tbody>
</table>

JS:

// 监听双击事件
$('.db-click').dblclick(function () {
    
    
	// 获取原值,同时去除空格回车
    let old_val = $(this).html().replace(/\s/g,"");

    // 给td塞进去一个input
    $(this).html("<input type='text' class='form-control db-input' value=" + old_val + " />");
	
	// 将光标移到input尾部,但是函数是在失焦时执行	
    $('.db-input').val('').focus().val(old_val).blur(function () {
    
    
    	// 获取当前值
        let new_val = $(this).val();

        // 将新值塞回到当前元素的父元素中
        $(this).parent().html(new_val);

        // 将修改后的结果提交到数据库
    })
})

注意最后需要将修改后的结果提交到数据库,这个需要在dbclick的回调函数中获取当前记录的id,然后用ajax提交到数据库就OK。

猜你喜欢

转载自blog.csdn.net/qq_42774234/article/details/129814869
今日推荐