Вот моя примерная таблица:
Код: Выделить всё
no. | button holder
-----------------------
2 | button here |
---------------------
2.1 | button here |
-----------------------
2.1.1 | button here |
-----------------------
2.1.1.1 | button here |
-----------------------
2.1.1.2 | button here |
-----------------------
2.2 | button here |
-----------------------
2.2.1 | button here |
-----------------------
2.2.2 | button here |
-----------------------
2.3 | button here |
-----------------------
- Если я нажму кнопку рядом с цифрой 2, я смогу создать 2.4 и добавлю его сразу после 2.3, поскольку последний дочерний элемент 2 — 2.3.
- Если я нажму кнопку рядом с 2.1.1, я смогу создать 2.1.1.3 и добавить его правильно. после 2.1.1.2, поскольку последним дочерним элементом 2.1.1 является 2.1.1.2
- Если я нажму кнопку рядом с 2.3, я смогу создать 2.3.1 и добавить его сразу после 2.3, поскольку у 2.3 еще нет дочерних элементов.
Вот моя текущая функция:
Код: Выделить всё
var currentButton;
var labelName;
var button_from;
function addChild(is_initial){
labelName = $('#childlabelName').val();
//ajax to save the new child
if(button_from == 'td'){
parent_id = child_id;
}
$.ajax({
method: 'post',
dataType: 'json',
data:{'get_action':'add_child', 'header_id':header_id, 'parent_id': parent_id, 'row_content': labelName},
success:function(response){
if(response.success == true){
$.confirm({
title: 'Success!',
content: 'Successfully added the new child.',
type: 'green',
typeAnimated: true,
buttons: {
close: function () {
if(button_from == 'th'){ //if button is clicked from the header
// Find the closest thead
var $thead = $(currentButton).closest('thead');
// Find the next tbody after this thead
var $nextTbody = $thead.next('tbody');
// Find the last row in the tbody
var $lastRow = $nextTbody.find('tr:last');
// Clone the last row
var $clonedRow = $lastRow.clone();
// Get the current row number from the last row's text
var lastRowNumberText = $lastRow.find('td:first').text();
var lastRowNumberParts = lastRowNumberText.split('.');
var newNumber = parseInt(lastRowNumberParts[1]) + 1;
// Update the number in the first td of the cloned row
var newNumberText = lastRowNumberParts[0] + '.' + newNumber;
$clonedRow.find('td:first').text(newNumberText);
// Optional: Clear input values in the cloned row
$clonedRow.find('input, textarea').val('');
// Get the header index
var get_index = $thead.index() / 2; // Assuming thead and tbody are alternating
// Get the index of the latest cloned row
var indexOfLatestRow = $nextTbody.find('tr').length;
// Update the label in the second td of the cloned row
var second_column_content = labelName +
'' +
'(+Add Child)' +
'';
$clonedRow.find('td:eq(1)').html(second_column_content);
// Update the names and IDs of form elements in the cloned row
$clonedRow.find('input, textarea').each(function() {
var old_name = $(this).attr('name');
var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id); // Replace the last part after underscore with row_id
$(this).attr('name', new_name);
});
// Add a delete button in the cloned row
//$clonedRow.find('td:last').html('[i][/i]');
clearFields($clonedRow);
// Append the cloned row to the correct tbody
$nextTbody.append($clonedRow);
}
if (button_from == 'td') {
var $closestTr = $(currentButton).closest('tr');
var $lastRowWithParentId = null;
var foundChild = false;
// Find the last row with the same parent_id
$closestTr.nextAll('tr').each(function() {
var $tdWithButton = $(this).find('td:eq(1)');
if ($tdWithButton.find('button').data('parent_id') == parent_id) {
$lastRowWithParentId = $(this);
foundChild = true;
} else if (foundChild) {
return false; // break loop if a non-child row is found after finding a child
}
});
// If no row with the same parent_id is found, find the row with data-id = parent_id
if (!$lastRowWithParentId) {
$closestTr.nextAll('tr').each(function() {
var $tdWithButton = $(this).find('td:eq(1)');
if ($tdWithButton.find('button').data('id') == parent_id) {
$lastRowWithParentId = $(this);
return false; // break loop once found
}
});
}
// Clone the row
var $rowToClone = $lastRowWithParentId ? $lastRowWithParentId : $closestTr;
var $clonedRow = $rowToClone.clone();
if ($closestTr.hasClass('parent')) {
$clonedRow.closest('tr').attr('class', 'child');
}
// Update hierarchical number
var newHierarchicalNumber = getNewHierarchicalNumber($rowToClone.find('td:first').text(), $closestTr);
$clonedRow.find('td:first').text(newHierarchicalNumber);
$clonedRow.find('input, textarea').val('');
// Update the label in the second td of the cloned row
var second_column_content = labelName +
'' +
'(+Add Child)' +
'';
$clonedRow.find('td:eq(1)').html(second_column_content);
$clonedRow.find('input, textarea').each(function() {
var old_name = $(this).attr('name');
var new_name = old_name.replace(/_[\d_]+$/, '_' + response.row_id);
$(this).attr('name', new_name);
});
// Insert the cloned row after the last row with the same parent_id or the current row
if ($lastRowWithParentId) {
$lastRowWithParentId.after($clonedRow);
} else {
$closestTr.after($clonedRow);
}
}
}
}
});
} else {
$.confirm({
title: 'Encountered an error!',
content: 'Failed to add the new child. Please refresh the page and try again. Contact the system\'s administrator if issue persists.',
type: 'red',
typeAnimated: true,
buttons: {
close: function () {
}
}
});
}
}
});
$('#childlabelName').val('');
}
function getNewHierarchicalNumber(currentNumber, $closestTr) {
var hierarchicalParts = currentNumber.split('.');
// Find all child rows of $closestTr
var $childRows = $closestTr.nextUntil('tr:not(.child)');
// If there are child rows, find the last one and increment its number
if ($childRows.length > 0) {
var lastChildNumber = $childRows.last().find('td:first').text();
var lastChildNumberParts = lastChildNumber.split('.');
hierarchicalParts = lastChildNumberParts;
hierarchicalParts[hierarchicalParts.length - 1] = parseInt(hierarchicalParts[hierarchicalParts.length - 1]) + 1;
} else {
// If no child rows, append ".1" to the current hierarchical number
hierarchicalParts.push('1');
}
return hierarchicalParts.join('.');
}
- нумерация
- размещение клонированной строки
Я попробовал добавить условие, при котором, если текущая строка находится при нажатии кнопки не существует дочернего элемента, тогда она просто скопирует номер и добавит к нему «.1». Он по-прежнему выдавал неправильные числа.
Обновление 2:
Я также пытался просто создать функцию, которая переупорядочивает все тело, но это не совсем правильно.
Когда я пытаюсь добавить 1.3.2 из существующей таблицы:
Код: Выделить всё
1.3
1.3.1
1.3.1.1
1.3.1.2
Код: Выделить всё
1.3
1.3.1
1.3.2
1.3.1.1
1.3.1.2
Код: Выделить всё
1.3
1.3.1
1.3.1.1
1.3.1.2
1.3.2
Код: Выделить всё
function reorderTableRows() {
var $table = $('#myTable');
var $tbody = $table.find('tbody');
// Clear existing tbody elements (optional, depending on your structure)
$tbody.empty();
// Recursive function to nest children rows
function nestChildren(parentId, $parentElement, level) {
var $children = $table.find('tr[data-parent_id="' + parentId + '"]');
if ($children.length > 0) {
// Sort children rows based on data-id
$children.sort(function(a, b) {
var idA = $(a).data('id');
var idB = $(b).data('id');
return idA - idB;
});
// Append sorted children rows under the parent element
$children.each(function() {
var $childRow = $(this);
var childId = $childRow.data('id');
// Find the previous sibling to insert after
var $prevSibling = $parentElement; // start with parent element
$parentElement.nextAll('tr').each(function() {
var $nextRow = $(this);
if ($nextRow.data('parent_id') == parentId && $nextRow.data('id') < childId) {
$prevSibling = $nextRow;
} else {
return false; // stop loop when we move past the relevant siblings
}
});
// Insert the child row after the previous sibling
$prevSibling.after($childRow);
// Recursively nest grandchildren
nestChildren(childId, $childRow, level + 1);
});
}
}
// Start nesting from top-level parent rows (where data-parent_id is null or undefined)
var $topLevelRows = $tbody.find('tr').filter(function() {
return !$(this).data('parent_id'); // Filter rows where data-parent_id is null or undefined
});
// Sort top-level rows based on data-id (optional, depending on your needs)
$topLevelRows.sort(function(a, b) {
var idA = $(a).data('id');
var idB = $(b).data('id');
return idA - idB;
});
// Append sorted top-level rows to tbody
$topLevelRows.each(function() {
var $row = $(this);
$tbody.append($row);
nestChildren($row.data('id'), $row, 1); // Start nesting children recursively
});
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... is-clicked