Он практиковал что-то простое в jquery, в этом случае добавлять новые линии к таблице через кнопку, для чего у меня есть два фрагмента кода:
Первый используя селектор tbody:last-child
и функция append()
jquery.
$("#add").on("click", function(){
$('#test > tbody:last-child').append('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test Tabla</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
И второй используя селектор tr:last
и функция after()
$("#add").on("click", function(){
$('#test tr:last').after('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Мой вопрос:
Существует какой-то другой способ это делать, и который двух форм наиболее осуществлен?
Да, существуют большие другие способы это делать, правда и со всем уважением я верю в то, что столькие, как мы смогли воображать и создавать. В SO на английском есть вопрос, который предлагает более 20 отличных выборов, чтобы это делать.
Которая из двух наиболее осуществлена? Я думаю, что нет большего различия, просто это два отличных способа решать проблему.
В условиях исходного кода использованных методов, различие между одним и другим должно бы быть минимальной частью в условиях результата:
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
В конце концов, относительно осуществления, которое снопы, могли бы улучшать незначительно селекторы, в первом случае не необходимо определять :last-child
и во втором мы могли бы предотвращать использование селектора потомок и добавлять tbody
, в случае, который был бы <tfoot>
в конце таблицы.
$("#add").on("click", function(){
$('#test > tbody').append('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test Tabla</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
$("#add").on("click", function(){
$('#test > tbody > tr:last').after('<tr><td>'+$("#nombre").val()+'</td><td>'+$("#apellido").val()+'</td></tr>');
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Nombre: <input type="text" id="nombre">
Apellido: <input type="text" id="apellido">
<button type="button" id="add">Agregar</button>
<table id="test">
<thead>
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Luis
</td>
<td>
Paredes
</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Добавляя в превосходный ответ @Shaz:
Которая из двух наиболее осуществлена?
Если ты имеешь в виду осуществление в общих условиях, ни одной. Избеги использовать этот тип кода no-reusable, в Вашем месте ты можешь использовать функции для этого, которые служили бы как шаблоны. Например, твой код могут modularizar так:
function addPerson(e) {
e.preventDefault();
const row = createRow({
name: $('#name').val(),
lastname: $('#lastname').val()
});
$('table tbody').append(row);
clean();
}
function createRow(data) {
return (
`<tr>` +
`<td>${$('tbody tr').length + 1}</td>` +
`<td>${data.name}</td>` +
`<td>${data.lastname}</td>` +
`</tr>`
);
}
function clean() {
$('#name').val('');
$('#lastname').val('');
$('#name').focus();
}
*,
*:before,
*:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
padding: 1rem;
text-align: center;
}
form {
display: inline-flex;
}
form input {
border: 1px solid #ccc;
color: #333;
font-family: 'segoe ui';
font-size: 14px;
outline: none;
padding: .4rem .8rem;
}
form button {
background-color: #1abc9c;
border: 1px solid #1abc9c;
color: rgba(255,255,255,.93);
font-family: 'segoe ui';
margin-left: 10px;
padding: .4rem 1rem;
transition: background-color .2s ease,
color .2s ease;
}
form button:hover {
background-color: #ffF;
color: #1abc9c;
}
table {
border-collapse: collapse;
border: 1px solid #ccc;
margin-top: 25px;
}
table thead th {
background-color: #f2f2f2;
font-weight: 500;
}
table thead th,
table tbody td {
color: #333;
font-family: 'segoe ui';
font-size: 14px;
padding: .5rem .65rem;
}
table thead th:not(:last-of-type),
table tbody td:not(:last-of-type) {
border-right: 1px solid #ccc;
}
table thead tr,
table tbody tr:not(:last-of-type) {
border-bottom: 1px solid #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form onsubmit="addPerson(event)">
<section class="group">
<input type="text" id="name" placeholder="Nombre" />
<input type="text" id="lastname" placeholder="Apellido" />
</section>
<button type="submit">Agregar</button>
</form>
<table style="display: inline-block">
<thead>
<tr>
<th>#</th>
<th>Nombre</th>
<th>Apellido</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
На результате между jQuery#append
и jQuery#after
, нет заметных различий.