基于jQuery的表格编辑器开发遇到的两个技术问题求助
Hey there! Let's tackle those two annoying issues with your table editing plugin one by one. I'll break down why each problem happens and show you the fully corrected code with extra user-friendly touches.
Issue 1: Existing Content Gets Cleared When Editing
What's Wrong?
Your original code uses $('input').focus().select(); which selects all text in the input box as soon as it's created. So when you start typing, you replace the entire existing content instead of editing parts of it.
The Fix
Either remove the .select() call to let users place their cursor normally, or add a helper function to move the cursor to the end of the text (so users can start typing after existing content without selecting everything).
Issue 2: Old Input Boxes Stay When Clicking New Cells
What's Wrong?
There was no logic to check for existing editable cells. Every new click just added a fresh input, leaving all previous ones in place until you pressed Enter.
The Fix
Track the currently editing cell, and when a new cell is clicked, first save and convert the old input back to plain text before creating the new input.
Full Corrected Code
JavaScript (jquery.workTables.js)
(function($) { // Helper function to move cursor to end of input (optional but user-friendly) function moveCursorToEnd(el) { el.focus(); if (typeof el.selectionStart === "number") { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange !== "undefined") { const range = el.createTextRange(); range.collapse(false); range.select(); } } $.fn.workTables = function() { let currentEditingTd = null; // Track the cell being edited $(this).click(function() { if (this.nodeName === "TD") { // First, save and close any existing editing cell if (currentEditingTd && currentEditingTd[0] !== this) { const activeInput = currentEditingTd.find('input'); if (activeInput.length) { currentEditingTd.text(activeInput.val()); } } // Convert current cell to input const cellText = $(this).text(); $(this).empty().append(`<input type="text" value="${cellText}">`); const input = $(this).find('input'); // Focus input and move cursor to end (remove moveCursorToEnd if you prefer default focus) moveCursorToEnd(input[0]); currentEditingTd = $(this); } }); // Handle Enter key to save changes $(this).on('keypress', 'input', function(e) { if (e.keyCode === 13) { const td = $(this).closest('td'); td.text($(this).val()); currentEditingTd = null; // Reset tracking } }); // Optional: Click outside to save changes $(document).click(function(e) { if (!$(e.target).closest('td').length && currentEditingTd) { const activeInput = currentEditingTd.find('input'); if (activeInput.length) { currentEditingTd.text(activeInput.val()); currentEditingTd = null; } } }); }; })(jQuery); // Initialize the plugin $(function() { $("td").workTables(); });
CSS
table, th, td { border: 1px solid black; border-collapse: collapse; /* Clean up border gaps */ padding: 8px; /* Add space for easier clicking/typing */ } input { width: 100%; /* Make input fill the entire cell */ box-sizing: border-box; /* Prevent overflow outside the cell */ padding: 6px; /* Match cell padding for consistency */ }
HTML
<!-- Only include one jQuery version (removed duplicate import) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="jquery.workTables.js"></script> <table style="width:100%"> <tr> <th></th> <th>Понедельник</th> <th>Вторник</th> <th>Среда</th> <th>Четверг</th> <th>Пятница</th> <th>Суббота</th> <th>Воскресенье</th> </tr> <tr> <td>1 пара 8:00 - 9:35</td> <td></td> <td></td> <td>Система технико-экономического анализа деятельности организации</td> <td>Программная и системная инженерия</td> <td></td> <td></td> <td></td> </tr> <tr> <td>2 пара 9:45 - 11:20</td> <td>Система технико-экономического анализа деятельности организации</td> <td>Веб-технологии</td> <td>Система технико-экономического анализа деятельности организации</td> <td>Программная и системная инженерия</td> <td></td> <td>Элективные курсы по физической культуре</td> <td></td> </tr> <tr> <td>3 пара 12:10 - 13:45</td> <td>Бизнес-аналитика и статистика</td> <td>Разработка приложений с использованием Oracle</td> <td>Элективные курсы по физической культуре</td> <td>Программная и системная инженерия</td> <td>Документирование создания информационных систем</td> <td></td> <td></td> </tr> <tr> <td>4 пара 13:55 - 15:30</td> <td>Бизнес-аналитика и статистика</td> <td>АИС в производстве</td> <td>Эконометрика</td> <td>Проектирование информационных систем</td> <td>Бизнес-аналитика и статистика</td> <td></td> <td></td> </tr> <tr> <td>5 пара 16:10 - 17:45</td> <td>Эконометрика</td> <td>Разработка приложений с использованием Oracle</td> <td></td> <td>Проектирование информационных систем</td> <td>Эконометрика</td> <td></td> <td></td> </tr> <tr> <td>6 пара 17:55 - 19:30</td> <td>Эконометрика</td> <td>АИС в производстве</td> <td></td> <td>Проектирование информационных систем</td> <td>Документирование создания информационных систем</td> <td></td> <td></td> </tr> <tr> <td>7 пара 20:05 - 2</td> </tr> </table>
Key Improvements Added
- Smart Cursor Placement: The helper function lets users edit existing content without accidentally replacing everything.
- Single Editable Cell: Only one cell can be edited at a time, with old inputs automatically converting back to text.
- Enter Key Fix: Now correctly saves only the current cell's input instead of targeting all inputs on the page.
- Click Outside to Save: Optional feature that saves changes when clicking anywhere outside the table.
- Cleaner UI: Added padding and border-collapse for a more polished look, plus input styling that fits perfectly in cells.
- Fixed jQuery Conflict: Removed duplicate jQuery imports which could cause unexpected bugs.
内容的提问来源于stack exchange,提问作者damirqasha

