Create editable table effects based on JQuery_jquery
WBOY
Release: 2016-05-16 16:24:54
Original
1108 people have browsed it
I recently worked on a project, and the project requirements are: click on the table to edit directly, press Enter or click elsewhere on the page to make the edit effective, press Esc to cancel the edit
Two friends gave 2 solutions. Let’s see which one is more suitable?
The first method to edit the table by clicking on it
//Equivalent to adding the onload event to the body tag in the page
$(function() {
//Find all td nodes
var tds = $("td");
//Add click events to all td
tds.click(function() {
//Get the currently clicked object
var td = $(this);
// Take out the text content of the current td and save it
var oldText = td.text();
//Create a text box and set the value of the text box to the saved value
var input = $("");
//Set the content of the current td object to input
td.html(input);
//Set the click event of the text box to be invalid
input.click(function() {
return false;
});
//Set the style of the text box
input.css("border-width", "0");
input.css("font-size", "16px");
input.css("text-align", "center");
//Set the width of the text box equal to the width of td
input.width(td.width());
//Trigger the select all event when the text box gets focus
input.trigger("focus").trigger("select");
//When the text box loses focus, it changes back to text
input.blur(function() {
var input_blur = $(this);
//Save the content of the current text box
var newText = input_blur.val();
td.html(newText);
});
//Response to keyboard events
input.keyup(function(event) {
// Get the key value
var keyEvent = event || window.event;
var key = keyEvent.keyCode;
//Get the current object
var input_blur = $(this);
switch (key)
{
case 13://Press the Enter key to save the contents of the current text box
var newText = input_blur.val();
td.html(newText);
break;
case 27://Press the esc key to cancel the modification and turn the text box into text
td.html(oldText);
break;
}
});
});
});
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