search
HomeWeb Front-endJS TutorialUsing jQuery to implement a simple editable table based on Bootstrap_javascript skills

editTable.js Provides operations for editing the current row of the table, adding a row, and deleting the current row. Parameters can be set, such as:

operatePos is used to set the column of the placement operation, starting from 0, -1 means using the last column as the column of the placement operation; (Operations here include editing the current row, adding a row under the current row, and deleting the current row)

handleFirst sets whether the first row of the table is used as the object of the operation, true is true, false is false;

edit, save, cancel, add, confirm and del respectively set the operation name of the display operation. By default, the words "edit", "save", "cancel", "add", "confirm" and "delete" are displayed;

editableCols sets the columns that can be edited, starting from 0, and is set in the form of an array, such as [1, 2], which means that the 2nd and 3rd columns can be edited when editing operations are performed; you can pass in "all", Indicates that all selected columns can be edited; of course, the program will automatically exclude columns that have been set to place operations;

order sets the operations required for the table, and can also set the order in which operations are arranged; the parameters are in the form of an array, and the values ​​in the array can be edit, add, or del; if an empty array is passed in, the edit operation will be provided by default, which is equivalent to setting [ "edit" ] parameter; in addition, all functions are provided by default, that is, editing, adding, and deleting, which is equivalent to setting the [ "edit", "add", "del"] parameters, and the order is edit-》add-》delete; it is possible Modify the order of the three, such as [ "add", "edit", "del" ];

saveCallback When the editing function is provided, during the process of editing the current row, click the callback function after saving; the user needs to set this parameter while using the editing function. When saving, the function can be passed using ajax Edited data data (saved in the data array), when ajax saves the data successfully, you should also call the isSuccess method in the function parameters to change the editable state in the interface to the uneditable state;

addCallback and delCallback are the same as saveCallback, but they are applied to different operations - add and delete.

editTable.js

/** 
 * Created by DreamBoy on 2016/4/19. 
 */ 
$(function() { 
 $.fn.handleTable = function (options) { 
  //1.Settings 初始化设置 
  var c = $.extend({ 
   "operatePos" : -1, //-1表示默认操作列为最后一列 
   "handleFirst" : false, //第一行是否作为操作的对象 
   "edit" : "编辑", 
   "save" : "保存", 
   "cancel" : "取消", 
   "add" : "添加", 
   "confirm" : "确认", 
   "del" : "删除", 
   "editableCols" : "all", //可编辑的列,从0开始 
   //"pos" : 0, //位置位于该列开头,还是结尾(左侧或右侧) 
   "order" : ["edit", "add", "del"], //指定三个功能的顺序 
   "saveCallback" : function(data, isSuccess) { //这里可以写ajax内容,用于保存编辑后的内容 
    //data: 返回的数据 
    //isSuccess: 方法,用于保存数据成功后,将可编辑状态变为不可编辑状态 
    //ajax请求成功(保存数据成功),才回调isSuccess函数(修改保存状态为编辑状态) 
   }, 
   "addCallback" : function(data, isSuccess) { 
    //isSuccess: 方法,用于添加数据成功后,将可编辑状态变为不可编辑状态 
   }, 
   "delCallback" : function(isSuccess) { 
    //isSuccess: 方法,用于删除数据成功后,将对应行删除 
   } 
  }, options); 
 
  //表格的列数 
  var colsNum = $(this).find('tr').last().children().size(); 
 
  //2.初始化操作列,默认为最后一列,从1算起 
  if(c.operatePos == -1) { 
   c.operatePos = colsNum - 1; 
  } 
 
  //3.获取所有需要被操作的行 
  var rows = $(this).find('tr'); 
  if(!c.handleFirst) { 
   rows = rows.not(":eq(0)"); 
  } 
 
  //4.获取放置“操作”的列,通过operatePos获取 
  var rowsTd = []; 
  var allTd = rows.children(); 
  for(var i = c.operatePos; i <= allTd.size(); i += colsNum) { 
   if(c.handleFirst) { //如果操作第一行,就把放置操作的列内容置为空 
    allTd.eq(i).html(""); 
   } 
   rowsTd.push(allTd.eq(i)[0]); 
  } 
 
  //6.修改设置 order 为空时的默认值 
  if(c.order.length == 0) { 
   c.order = ["edit"]; 
  } 
 
  //7.保存可编辑的列 
  var cols = getEditableCols(); 
 
  //8.初始化链接的构建 
  var saveLink = "", cancelLink = "", editLink = "", addLink = "", confirmLink = "", delLink = ""; 
  initLink(); 
 
  //9.初始化操作 
  initFunc(c.order, rowsTd); 
 
  /** 
   * 创建操作链接 
   */ 
  function createLink(str) { 
   return "<a href=\"javascript:void(0)\" style=\"margin:0 3px\">" + str + "</a>"; 
  } 
  /** 
   * 初始各种操作的链接 
   */ 
  function initLink() { 
   for(var i = 0; i < c.order.length; i++) { 
    switch (c.order[i]) { 
     case "edit": 
      //“编辑”链接 
      editLink = createLink(c.edit); 
      saveLink = createLink(c.save); 
      cancelLink = createLink(c.cancel); 
      break; 
     case "add": 
      //“添加”链接 
      addLink = createLink(c.add); 
      //“确认”链接 
      confirmLink = createLink(c.confirm); 
      //“取消”链接 
      cancelLink = createLink(c.cancel); 
      break; 
     case "del": 
      //“删除”链接 
      delLink = createLink(c.del); 
      break; 
    } 
   } 
  } 
 
  /** 
   * 获取可进行编辑操作的列 
   */ 
  function getEditableCols() { 
   var cols = c.editableCols; 
   if($.type(c.editableCols) != "array" && cols == "all") { //如果是所有列都可以编辑的话 
    cols = []; 
    for(var i = 0; i < colsNum; i++) { 
     if(i != c.operatePos) { //排除放置操作的列 
      cols.push(i); 
     } 
    } 
   } else if($.type(c.editableCols) == "array") { //有指定选择编辑的列的话需要排序放置“编辑”功能的列 
    var copyCols = []; 
    for(var i = 0; i < cols.length; i++) { 
     if(cols[i] != c.operatePos) { 
      copyCols.push(cols[i]); 
     } 
    } 
    cols = copyCols; 
   } 
   return cols; 
  } 
 
  /** 
   * 根据c.order参数设置提供的操作 
   * @param func 需要设置的操作 
   * @param cols 放置操作的列 
   */ 
  function initFunc(func, cols) { 
   for(var i = 0; i < func.length; i++) { 
    var o = func[i]; 
    switch(o) { 
     case "edit": 
      createEdit(cols); 
      break; 
     case "add": 
      createAdd(cols); 
      break; 
     case "del": 
      createDel(cols); 
      break; 
    } 
   } 
  } 
 
  /** 
   * 创建“编辑一行”的功能 
   * @param operateCol 放置编辑操作的列 
   */ 
  function createEdit(operateCol) { 
   $(editLink).appendTo(operateCol).on("click", function() { 
    if(replaceQuote($(this).html()) == replaceQuote(c.edit)) { //如果此时是编辑状态 
     toSave(this); //将编辑状态变为保存状态 
    } else if(replaceQuote($(this).html()) == replaceQuote(c.save)) { //如果此时是保存状态 
     var p = $(this).parents('tr'); //获取被点击的当前行 
     var data = []; //保存修改后的数据到数据内 
     for(var i = 0; i < cols.length; i++) { 
      var tr = p.children().eq(cols[i]); 
      var inputValue = tr.children('input').val(); 
      data.push(inputValue); 
     } 
 
     $this = this; //此时的this表示的是 被点击的 编辑链接 
     c.saveCallback(data, function() { 
      toEdit($this, true); 
     }); 
    } 
   }); 
   var afterSave = []; //保存修改前的信息,用于用户点击取消后的数值返回操作 
   //修改为“保存”状态 
   function toSave(ele) { 
    $(ele).html(c.save); //修改为“保存” 
    $(ele).after(cancelLink); //添加相应的取消保存的“取消链接” 
    $(ele).next().on('click', function() { 
     //if($(this).html() == c.cancel.replace(eval("/\'/gi"),"\"")) { 
     toEdit(ele, false); 
     //} 
    }); 
 
    //获取被点击编辑的当前行 tr jQuery对象 
    var p = $(ele).parents('tr'); 
 
    afterSave = []; //清空原来保存的数据 
    for(var i = 0; i < cols.length; i++) { 
     var tr = p.children().eq(cols[i]); 
     var editTr = "<input type=\"text\" class=\"form-control\" value=\"" + tr.html() + "\"/>"; 
     afterSave.push(tr.html()); //保存未修改前的数据 
     tr.html(editTr); 
    } 
   } 
   //修改为“编辑”状态(此时,需要通过isSave标志判断是 
   // 因为点击了“保存”(保存成功)变为“编辑”状态的,还是因为点击了“取消”变为“编辑”状态的) 
   function toEdit(ele, isSave) { 
    $(ele).html(c.edit); 
    if(replaceQuote($(ele).next().html()) == replaceQuote(c.cancel)) { 
     $(ele).next().remove(); 
    } 
 
    var p = $(ele).parents('tr'); 
 
    for(var i = 0; i < cols.length; i++) { 
     var tr = p.children().eq(cols[i]); 
     var value; 
     if(isSave) { 
      value = tr.children('input').val(); 
     } else { 
      value = afterSave[i]; 
     } 
 
     tr.html(value); 
    } 
   } 
  } 
 
  /** 
   * 创建“添加一行”的功能 
   * @param operateCol 
   */ 
  function createAdd(operateCol) { 
   $(addLink).appendTo(operateCol).on("click", function() { 
    //获取被点击“添加”的当前行 tr jQuery对象 
    var p = $(this).parents('tr'); 
    var copyRow = p.clone(); //构建新的一行 
    var input = "<input type=\"text\"/>"; 
    var childLen = p.children().length; 
    for(var i = 0; i < childLen; i++) { 
     copyRow.children().eq(i).html("<input type=\"text\" class=\"form-control\"/>"); 
    } 
 
    //最后一行是操作行 
    var last = copyRow.children().eq(c.operatePos); 
    last.html(""); 
    p.after(copyRow); 
 
    var confirm = $(confirmLink).appendTo(last).on("click", function() { 
     var data = []; 
     for(var i = 0; i < childLen; i++) { 
      if(i != c.operatePos) { 
       var v = copyRow.children().eq(i).children("input").val(); 
       data.push(v); 
       copyRow.children().eq(i).html(v); 
      } 
     } 
     c.addCallback(data, function() { 
      last.html(""); 
      //------------这里可以进行修改 
      initFunc(c.order, last); 
     }); 
    }); 
 
    $(confirm).after(cancelLink); //添加相应的取消保存的“取消链接” 
    $(confirm).next().on('click', function() { 
     copyRow.remove(); 
    }); 
   }); 
  } 
 
  /** 
   * 创建“删除一行”的功能 
   * @param operateCol 
   */ 
  function createDel(operateCol) { 
   $(delLink).appendTo(operateCol).on("click", function() { 
    var _this = this; 
    c.delCallback(function() { 
     $(_this).parents('tr').remove(); 
    }); 
   }); 
  } 
 
  /** 
   * 将str中的单引号转为双引号 
   * @param str 
   */ 
  function replaceQuote(str) { 
   return str.replace(/\'/g, "\""); 
  } 
 }; 
}); 

You need to pay attention during use: you need to add selectable selectors to the corresponding table, and you need to place an empty label in the column where the "operation" is placed

for storing the "operation" ".

Use cases are as follows:

Directory structure:


index.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
 <meta charset="UTF-8"> 
 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 <meta name="viewport" content="width=device-width, initial-scale=1"> 
 <title>表格</title> 
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"> 
 <!--<link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />--> 
 <!--[if lt IE 9]> 
 <script src="js/html5shiv.js"></script> 
 <script src="js/respond.min.js"></script> 
 <![endif]--> 
</head> 
<body> 
 <div class="container"> 
  <div class="bs-example" data-example-id="hoverable-table"> 
   <table class="table table-hover editable"> 
    <thead> 
    <tr> 
     <th>#</th> 
     <th>Test</th> 
     <th>First Name</th> 
     <th>Last Name</th> 
     <th>Username</th> 
     <th>Operations</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <th scope="row">1</th> 
     <td></td> 
     <td>Mark</td> 
     <td>Otto</td> 
     <td>@mdo</td> 
     <td><!--<a href="javascript:void(0)" class="edit"></a>--></td> 
    </tr> 
    <tr> 
     <th scope="row">2</th> 
     <td></td> 
     <td>Jacob</td> 
     <td>Thornton</td> 
     <td>@fat</td> 
     <td><!--<a href="javascript:void(0)" class="edit"></a>--></td> 
    </tr> 
    <tr> 
     <th scope="row">3</th> 
     <td></td> 
     <td>Larry</td> 
     <td>the Bird</td> 
     <td>@twitter</td> 
     <td><!--<a href="javascript:void(0)" class="edit"></a>--></td> 
    </tr> 
    </tbody> 
   </table> 
  </div> 
 </div> 
 
 <script src="js/jquery-1.11.1.min.js"></script> 
 <script src="js/bootstrap.min.js"></script> 
 <script src="editTable.js"></script> 
 <script> 
  $(function() { 
   //$('.edit').handleTable({"cancel" : "<span class='glyphicon glyphicon-remove'></span>"}); 
   $('.editable').handleTable({ 
    "handleFirst" : true, 
    "cancel" : " <span class='glyphicon glyphicon-remove'></span> ", 
    "edit" : " <span class='glyphicon glyphicon-edit'></span> ", 
    "add" : " <span class='glyphicon glyphicon-plus'></span> ", 
    "save" : " <span class='glyphicon glyphicon-saved'></span> ", 
    "confirm" : " <span class='glyphicon glyphicon-ok'></span> ", 
    "operatePos" : -1, 
    "editableCols" : [2,3,4], 
    "order": ["add","edit"], 
    "saveCallback" : function(data, isSuccess) { //这里可以写ajax内容,用于保存编辑后的内容 
     //data: 返回的数据 
     //isSucess: 方法,用于保存数据成功后,将可编辑状态变为不可编辑状态 
     var flag = true; //ajax请求成功(保存数据成功),才回调isSuccess函数(修改保存状态为编辑状态) 
     if(flag) { 
      isSuccess(); 
      alert(data + " 保存成功"); 
     } else { 
      alert(data + " 保存失败"); 
     } 
 
     return true; 
    }, 
    "addCallback" : function(data,isSuccess) { 
     var flag = true; 
     if(flag) { 
      isSuccess(); 
      alert(data + " 增加成功"); 
     } else { 
      alert(data + " 增加失败"); 
     } 
    }, 
    "delCallback" : function(isSuccess) { 
     var flag = true; 
     if(flag) { 
      isSuccess(); 
      alert("删除成功"); 
     } else { 
      alert("删除失败"); 
     } 
    } 
   }); 
  }); 
 </script> 
</body> 
</html> 

The running results are as follows


Use editing actions:

Make changes:


Click to save:


Add multiple lines:


Add some data in there:


Click "OK":



You can cancel other redundant lines to be added:


The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),